Реализовать lab3 на оценку 4: балансировка и отказ API
This commit is contained in:
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const ProfileTTL = 60 * time.Second
|
||||
|
||||
type Profiles struct{ client *redis.Client }
|
||||
|
||||
func NewProfiles(address string) *Profiles {
|
||||
return &Profiles{client: redis.NewClient(&redis.Options{
|
||||
Addr: address,
|
||||
Protocol: 2,
|
||||
MaxRetries: -1,
|
||||
DialTimeout: 200 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolTimeout: 200 * time.Millisecond,
|
||||
ContextTimeoutEnabled: true,
|
||||
PoolSize: 10,
|
||||
MaxActiveConns: 10,
|
||||
MinIdleConns: 0,
|
||||
})}
|
||||
}
|
||||
|
||||
func (p *Profiles) Close() error { return p.client.Close() }
|
||||
|
||||
func (p *Profiles) Get(ctx context.Context, id string) (model.User, bool) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
defer cancel()
|
||||
raw, err := p.client.Get(ctx, "profile:v1:"+id).Bytes()
|
||||
if err != nil {
|
||||
return model.User{}, false
|
||||
}
|
||||
var user model.User
|
||||
if json.Unmarshal(raw, &user) != nil || user.ID != id || user.Username == "" || user.DisplayName == "" || user.CreatedAt.IsZero() {
|
||||
return model.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (p *Profiles) Set(ctx context.Context, user model.User) {
|
||||
raw, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
defer cancel()
|
||||
_ = p.client.Set(ctx, "profile:v1:"+user.ID, raw, ProfileTTL).Err()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
type userContextKey struct{}
|
||||
|
||||
func (api *API) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := api.messenger.CurrentUser(r.Header.Get("X-User-Id"))
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func userFromContext(ctx context.Context) model.User {
|
||||
return ctx.Value(userContextKey{}).(model.User)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
actor := userFromContext(r.Context())
|
||||
|
||||
if r.URL.Path == "/api/v1/chats" {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createChatRequest
|
||||
if !readJSON(w, r, &body, "title", "member_ids") {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.CreateChat(
|
||||
actor.ID, body.Title, body.MemberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListChats(actor.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
if len(parts) == 1 && parts[0] != "" {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return
|
||||
}
|
||||
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createMessageRequest
|
||||
if !readJSON(w, r, &body, "text") {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := api.messenger.CreateMessage(
|
||||
actor.ID, chat.ID, body.Text,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListMessages(
|
||||
actor.ID, chat.ID, limit, cursor,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
}
|
||||
|
||||
func pageParams(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (int, string, bool) {
|
||||
invalid := func() (int, string, bool) {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return 0, "", false
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
limit := 50
|
||||
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
for _, char := range values[0] {
|
||||
if char < '0' || char > '9' {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
limit = value
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return invalid()
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type chatTestClient struct {
|
||||
base string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newChatTestClient(t *testing.T) *chatTestClient {
|
||||
t.Helper()
|
||||
|
||||
server := httptest.NewServer(newAPI())
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client := server.Client()
|
||||
client.Timeout = 10 * time.Second
|
||||
|
||||
return &chatTestClient{
|
||||
base: server.URL,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatTestClient) call(
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
wantStatus int,
|
||||
result any,
|
||||
) error {
|
||||
var encoded []byte
|
||||
var err error
|
||||
|
||||
if body != nil {
|
||||
encoded, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(
|
||||
method,
|
||||
c.base+path,
|
||||
bytes.NewReader(encoded),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actorID != "" {
|
||||
req.Header.Set("X-User-Id", actorID)
|
||||
}
|
||||
|
||||
response, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if response.StatusCode != wantStatus {
|
||||
return fmt.Errorf(
|
||||
"%s %s: status=%d, want=%d, body=%s",
|
||||
method, path, response.StatusCode, wantStatus, data,
|
||||
)
|
||||
}
|
||||
|
||||
requestID := response.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
return fmt.Errorf("%s %s: missing request ID", method, path)
|
||||
}
|
||||
|
||||
if wantStatus >= 400 {
|
||||
var problem struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &problem); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if problem.Error.Code == "" ||
|
||||
problem.Error.RequestID != requestID {
|
||||
return fmt.Errorf("invalid error response: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
return json.Unmarshal(data, result)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mustCall(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
status int,
|
||||
result any,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if err := c.call(method, path, actorID, body, status, result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func createTestUser(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
username string,
|
||||
) model.User {
|
||||
t.Helper()
|
||||
|
||||
var user model.User
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/users", "",
|
||||
map[string]any{
|
||||
"username": username,
|
||||
"display_name": username,
|
||||
},
|
||||
http.StatusCreated, &user,
|
||||
)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func createTestChat(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
members []string,
|
||||
) model.Chat {
|
||||
t.Helper()
|
||||
|
||||
var chat model.Chat
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", actorID,
|
||||
map[string]any{
|
||||
"title": "Test chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusCreated, &chat,
|
||||
)
|
||||
|
||||
return chat
|
||||
}
|
||||
|
||||
func readAllMessages(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
) ([]model.Message, int) {
|
||||
t.Helper()
|
||||
|
||||
var messages []model.Message
|
||||
cursor := ""
|
||||
pages := 0
|
||||
seenCursors := make(map[string]bool)
|
||||
|
||||
for {
|
||||
path := fmt.Sprintf(
|
||||
"/api/v1/chats/%s/messages?limit=%d",
|
||||
chatID, limit,
|
||||
)
|
||||
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
var page service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, actorID,
|
||||
nil, http.StatusOK, &page,
|
||||
)
|
||||
|
||||
pages++
|
||||
|
||||
if page.Items == nil {
|
||||
t.Fatal("items must be an array, not null")
|
||||
}
|
||||
if len(page.Items) > limit {
|
||||
t.Fatal("page exceeds requested limit")
|
||||
}
|
||||
|
||||
messages = append(messages, page.Items...)
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = *page.NextCursor
|
||||
if cursor == "" || seenCursors[cursor] || pages > 100 {
|
||||
t.Fatal("invalid or repeating pagination cursor")
|
||||
}
|
||||
seenCursors[cursor] = true
|
||||
}
|
||||
|
||||
return messages, pages
|
||||
}
|
||||
|
||||
func TestChatAccessAndValidation(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
alice := createTestUser(t, c, "alice")
|
||||
bob := createTestUser(t, c, "bob")
|
||||
eve := createTestUser(t, c, "eve")
|
||||
|
||||
chat := createTestChat(
|
||||
t, c, alice.ID, []string{alice.ID, bob.ID},
|
||||
)
|
||||
path := "/api/v1/chats/" + chat.ID
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"/messages", eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", eve.ID,
|
||||
map[string]any{"text": "not allowed"},
|
||||
http.StatusNotFound, nil,
|
||||
)
|
||||
|
||||
var hidden service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", eve.ID,
|
||||
nil, http.StatusOK, &hidden,
|
||||
)
|
||||
if len(hidden.Items) != 0 {
|
||||
t.Fatal("outsider sees a private chat")
|
||||
}
|
||||
|
||||
for _, text := range []string{"", " \t\n"} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{
|
||||
"text": "hello",
|
||||
"sender_id": bob.ID,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, members := range [][]string{
|
||||
{alice.ID, alice.ID},
|
||||
{bob.ID},
|
||||
{alice.ID, "00000000-0000-4000-8000-000000000000"},
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", alice.ID,
|
||||
map[string]any{
|
||||
"title": "Invalid chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
var chats service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", alice.ID,
|
||||
nil, http.StatusOK, &chats,
|
||||
)
|
||||
if len(chats.Items) != 1 {
|
||||
t.Fatalf("expected one chat, got %d", len(chats.Items))
|
||||
}
|
||||
|
||||
messages, _ := readAllMessages(t, c, alice.ID, chat.ID, 10)
|
||||
if len(messages) != 0 {
|
||||
t.Fatal("rejected messages were saved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagePagination(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
alice := createTestUser(t, c, "alice")
|
||||
|
||||
chat := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
other := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
var sent []model.Message
|
||||
|
||||
for i := 0; i < 7; i++ {
|
||||
var message model.Message
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path, alice.ID,
|
||||
map[string]any{"text": fmt.Sprintf("Сообщение %d 👋", i)},
|
||||
http.StatusCreated, &message,
|
||||
)
|
||||
sent = append(sent, message)
|
||||
}
|
||||
|
||||
got, pages := readAllMessages(t, c, alice.ID, chat.ID, 2)
|
||||
|
||||
if len(got) != len(sent) || pages != 4 {
|
||||
t.Fatalf("got %d messages on %d pages", len(got), pages)
|
||||
}
|
||||
|
||||
for i := range sent {
|
||||
if got[i] != sent[i] {
|
||||
t.Fatalf("message %d differs or is out of order", i)
|
||||
}
|
||||
}
|
||||
|
||||
var first service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?limit=2", alice.ID,
|
||||
nil, http.StatusOK, &first,
|
||||
)
|
||||
|
||||
if first.NextCursor == nil {
|
||||
t.Fatal("expected next cursor")
|
||||
}
|
||||
|
||||
cursor := url.QueryEscape(*first.NextCursor)
|
||||
|
||||
var next service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
path+"?limit=3&cursor="+cursor, alice.ID,
|
||||
nil, http.StatusOK, &next,
|
||||
)
|
||||
|
||||
if len(next.Items) != 3 || next.Items[0].ID != sent[2].ID {
|
||||
t.Fatal("changing page size lost or repeated a message")
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
"/api/v1/chats/"+other.ID+"/messages?cursor="+cursor,
|
||||
alice.ID, nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, query := range []string{
|
||||
"limit=0",
|
||||
"limit=101",
|
||||
"limit=abc",
|
||||
"cursor=invalid",
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?"+query, alice.ID,
|
||||
nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessages100From10Clients(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
const clients = 10
|
||||
const messagesPerClient = 10
|
||||
const total = clients * messagesPerClient
|
||||
|
||||
users := make([]model.User, clients)
|
||||
memberIDs := make([]string, clients)
|
||||
|
||||
for i := range users {
|
||||
users[i] = createTestUser(t, c, fmt.Sprintf("user_%02d", i))
|
||||
memberIDs[i] = users[i].ID
|
||||
}
|
||||
|
||||
chat := createTestChat(t, c, users[0].ID, memberIDs)
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
type outcome struct {
|
||||
message model.Message
|
||||
err error
|
||||
}
|
||||
|
||||
results := make(chan outcome, total)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for clientIndex := 0; clientIndex < clients; clientIndex++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
for j := 0; j < messagesPerClient; j++ {
|
||||
text := fmt.Sprintf("client-%d-message-%d", index, j)
|
||||
var message model.Message
|
||||
|
||||
err := c.call(
|
||||
http.MethodPost,
|
||||
path,
|
||||
users[index].ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusCreated,
|
||||
&message,
|
||||
)
|
||||
|
||||
if err == nil &&
|
||||
(message.SenderID != users[index].ID ||
|
||||
message.Text != text ||
|
||||
message.ChatID != chat.ID) {
|
||||
err = fmt.Errorf("incorrect message response")
|
||||
}
|
||||
|
||||
results <- outcome{message: message, err: err}
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
expected := make(map[string]model.Message, total)
|
||||
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Errorf("send failed: %v", result.err)
|
||||
continue
|
||||
}
|
||||
|
||||
if _, exists := expected[result.message.ID]; exists {
|
||||
t.Errorf("duplicate response ID: %s", result.message.ID)
|
||||
}
|
||||
|
||||
expected[result.message.ID] = result.message
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
if len(expected) != total {
|
||||
t.Fatalf("expected %d unique responses, got %d", total, len(expected))
|
||||
}
|
||||
|
||||
history, pages := readAllMessages(
|
||||
t, c, users[0].ID, chat.ID, 17,
|
||||
)
|
||||
|
||||
if len(history) != total {
|
||||
t.Fatalf("expected %d stored messages, got %d", total, len(history))
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, total)
|
||||
|
||||
for _, message := range history {
|
||||
if seen[message.ID] {
|
||||
t.Fatalf("duplicate history ID: %s", message.ID)
|
||||
}
|
||||
seen[message.ID] = true
|
||||
|
||||
want, exists := expected[message.ID]
|
||||
if !exists || want != message {
|
||||
t.Fatalf("missing or changed message: %s", message.ID)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf(
|
||||
"clients=%d sent=%d unique_responses=%d stored=%d unique_stored=%d pages=%d",
|
||||
clients, total, len(expected), len(history), len(seen), pages,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func writeAppError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", "Idempotency key already used for another message")
|
||||
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable")
|
||||
|
||||
case errors.Is(err, service.ErrInvalidRequest):
|
||||
writeError(
|
||||
w, http.StatusBadRequest,
|
||||
"invalid_request", "Invalid request fields",
|
||||
)
|
||||
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
writeError(
|
||||
w, http.StatusUnauthorized,
|
||||
"unauthorized", "Valid X-User-Id is required",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
writeError(
|
||||
w, http.StatusConflict,
|
||||
"conflict", "Username already exists",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrInvalidMembers):
|
||||
writeError(
|
||||
w, http.StatusBadRequest,
|
||||
"invalid_request", "Invalid chat members",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
writeError(
|
||||
w, http.StatusNotFound,
|
||||
"not_found", "Resource not found",
|
||||
)
|
||||
|
||||
default:
|
||||
log.Printf(
|
||||
"internal error request_id=%s: %v",
|
||||
w.Header().Get("X-Request-Id"),
|
||||
err,
|
||||
)
|
||||
|
||||
writeError(
|
||||
w, http.StatusInternalServerError,
|
||||
"internal_error", "Internal server error",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(
|
||||
w http.ResponseWriter,
|
||||
status int,
|
||||
code string,
|
||||
message string,
|
||||
) {
|
||||
writeJSON(w, status, errorResponse{
|
||||
Error: errorDetails{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: w.Header().Get("X-Request-Id"),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import "net/http"
|
||||
|
||||
func handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
|
||||
writeError(
|
||||
w,
|
||||
http.StatusMethodNotAllowed,
|
||||
"invalid_request",
|
||||
"Method not allowed",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Status string `json:"status"`
|
||||
}{
|
||||
Status: "ok",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func TestInstanceIDOnResponses(t *testing.T) {
|
||||
var stopping atomic.Bool
|
||||
handler, err := httpapi.NewPostgresHandler(&store.PostgresStore{}, &stopping, 3600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var instanceID string
|
||||
for _, tc := range []struct {
|
||||
path string
|
||||
stopping bool
|
||||
status int
|
||||
}{
|
||||
{"/health/live", false, http.StatusOK},
|
||||
{"/missing", false, http.StatusNotFound},
|
||||
{"/api/v1/chats", false, http.StatusUnauthorized},
|
||||
{"/health/ready", true, http.StatusServiceUnavailable},
|
||||
{"/health/live", true, http.StatusOK},
|
||||
} {
|
||||
stopping.Store(tc.stopping)
|
||||
response := request(handler, http.MethodGet, tc.path, "", "")
|
||||
if response.Code != tc.status {
|
||||
t.Fatalf("%s: status=%d, want %d", tc.path, response.Code, tc.status)
|
||||
}
|
||||
got := response.Header().Get("X-Instance-Id")
|
||||
if got == "" {
|
||||
t.Fatal("missing X-Instance-Id")
|
||||
}
|
||||
if instanceID != "" && got != instanceID {
|
||||
t.Fatalf("instance changed: %q -> %q", instanceID, got)
|
||||
}
|
||||
instanceID = got
|
||||
}
|
||||
response := request(newAPI(), http.MethodGet, "/health/live", "", "")
|
||||
if got := response.Header().Get("X-Instance-Id"); got != instanceID {
|
||||
t.Fatalf("different handlers in one process: %q != %q", got, instanceID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"slices"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxJSONBody = 1 << 20 // 1 MiB
|
||||
|
||||
func readJSON(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
dst any,
|
||||
requiredFields ...string,
|
||||
) bool {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
"unsupported_media_type",
|
||||
"Content-Type must be application/json",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBody+1))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Cannot read body")
|
||||
return false
|
||||
}
|
||||
|
||||
if len(body) > maxJSONBody {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
"payload_too_large",
|
||||
"JSON body is too large",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
invalid := func() bool {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"Invalid JSON body",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &fields); err != nil || fields == nil {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
for name := range fields {
|
||||
if !slices.Contains(requiredFields, name) {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range requiredFields {
|
||||
value, exists := fields[name]
|
||||
if !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
log.Printf("cannot write JSON response: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
func TestJSONFieldNamesAreCaseSensitive(t *testing.T) {
|
||||
handler := newAPI()
|
||||
|
||||
t.Run("registration", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"username":"alice","display_name":"Original","Display_Name":"Changed"}`,
|
||||
`{"Display_Name":"Changed","username":"alice","display_name":"Original"}`,
|
||||
`{"username":"alice","display_name":"Original","Username":"bob"}`,
|
||||
`{"username":"alice","Display_Name":"Changed"}`,
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, "/api/v1/users", body, ""),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
})
|
||||
|
||||
created := request(handler, http.MethodPost, "/api/v1/users",
|
||||
`{"username":"alice","display_name":"Original"}`, "")
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("valid registration: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
var user model.User
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user.DisplayName != "Original" {
|
||||
t.Fatalf("display name changed: %q", user.DisplayName)
|
||||
}
|
||||
|
||||
t.Run("chat", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
fmt.Sprintf(`{"title":"Original","Title":"Changed","member_ids":[%q]}`, user.ID),
|
||||
fmt.Sprintf(`{"Title":"Changed","title":"Original","member_ids":[%q]}`, user.ID),
|
||||
fmt.Sprintf(`{"title":"Original","member_ids":[%q],"Member_Ids":[]}`, user.ID),
|
||||
fmt.Sprintf(`{"Title":"Changed","member_ids":[%q]}`, user.ID),
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, "/api/v1/chats", body, user.ID),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
response := request(handler, http.MethodGet, "/api/v1/chats", "", user.ID)
|
||||
var page service.Page[model.Chat]
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusOK || len(page.Items) != 0 {
|
||||
t.Fatalf("rejected chats were saved: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
created = request(handler, http.MethodPost, "/api/v1/chats",
|
||||
fmt.Sprintf(`{"title":"Original","member_ids":[%q]}`, user.ID), user.ID)
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("valid chat: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
var chat model.Chat
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &chat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
t.Run("message", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"text":"Original","Text":"Changed"}`,
|
||||
`{"Text":"Changed","text":"Original"}`,
|
||||
`{"text":"Original","TEXT":"Changed"}`,
|
||||
`{"Text":"Changed"}`,
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, path, body, user.ID),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
response := request(handler, http.MethodGet, path, "", user.ID)
|
||||
var page service.Page[model.Message]
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusOK || len(page.Items) != 0 {
|
||||
t.Fatalf("rejected messages were saved: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
response = request(handler, http.MethodPost, path, `{"text":"Original"}`, user.ID)
|
||||
var message model.Message
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusCreated || message.Text != "Original" {
|
||||
t.Fatalf("valid message: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var processInstanceID = rand.Text()
|
||||
|
||||
func withInstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", processInstanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var randomBytes [16]byte
|
||||
|
||||
if _, err := rand.Read(randomBytes[:]); err != nil {
|
||||
panic("cannot generate request ID")
|
||||
}
|
||||
|
||||
requestID := hex.EncodeToString(randomBytes[:])
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
if w.status != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(body []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
||||
return w.ResponseWriter
|
||||
}
|
||||
|
||||
func withAccessLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
log.Printf(
|
||||
"handler panic request_id=%s",
|
||||
writer.Header().Get("X-Request-Id"),
|
||||
)
|
||||
|
||||
if writer.status == 0 {
|
||||
writeError(
|
||||
writer,
|
||||
http.StatusInternalServerError,
|
||||
"internal_error",
|
||||
"Internal server error",
|
||||
)
|
||||
} else {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
|
||||
status := writer.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"request_id=%s method=%s path=%q status=%d duration_ms=%d",
|
||||
writer.Header().Get("X-Request-Id"),
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
status,
|
||||
time.Since(started).Milliseconds(),
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) {
|
||||
registration := service.NewRegistration(db)
|
||||
sessions, err := service.NewSessions(db, registration, ttl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)}
|
||||
return withInstanceID(withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if stopping.Load() && r.URL.Path != "/health/live" {
|
||||
writeAppError(w, store.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
|
||||
token, err := bearerToken(r)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
user, err := sessions.CurrentUser(r.Context(), token)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, user)
|
||||
chats.chatRoutes(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/auth/sessions":
|
||||
loginSession(w, r, sessions)
|
||||
case "/api/v1/auth/sessions/current":
|
||||
currentSession(w, r, sessions, true)
|
||||
case "/api/v1/users/me":
|
||||
currentSession(w, r, sessions, false)
|
||||
case "/health/live":
|
||||
handleHealth(w, r)
|
||||
case "/health/ready":
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
if err := db.Ping(r.Context()); err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
handleHealth(w, r)
|
||||
case "/api/v1/users":
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !readJSON(w, r, &body, "username", "display_name", "password") {
|
||||
return
|
||||
}
|
||||
user, err := registration.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
}
|
||||
})))), nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type persistentAPI struct{ messenger *service.PersistentMessenger }
|
||||
|
||||
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
actor := userFromContext(r.Context())
|
||||
|
||||
if r.URL.Path == "/api/v1/chats" {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createChatRequest
|
||||
if !readJSON(w, r, &body, "title", "member_ids") {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.CreateChat(r.Context(),
|
||||
actor.ID, body.Title, body.MemberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListChats(r.Context(), actor.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
if len(parts) == 1 && parts[0] != "" {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return
|
||||
}
|
||||
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createMessageRequest
|
||||
if !readJSON(w, r, &body, "text") {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := api.messenger.CreateMessage(r.Context(),
|
||||
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"),
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListMessages(r.Context(),
|
||||
actor.ID, chat.ID, limit, cursor,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type API struct {
|
||||
messenger *service.Messenger
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
messenger *service.Messenger,
|
||||
stoppingFlags ...*atomic.Bool,
|
||||
) http.Handler {
|
||||
api := &API{messenger: messenger}
|
||||
|
||||
var stopping *atomic.Bool
|
||||
|
||||
if len(stoppingFlags) > 0 {
|
||||
stopping = stoppingFlags[0]
|
||||
}
|
||||
|
||||
if stopping == nil {
|
||||
stopping = &atomic.Bool{}
|
||||
}
|
||||
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if stopping.Load() && r.URL.Path != "/health/live" {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
"unavailable",
|
||||
"Server is shutting down",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
api.route(w, r)
|
||||
})
|
||||
|
||||
return withInstanceID(withRequestID(withAccessLog(handler)))
|
||||
}
|
||||
|
||||
func (api *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/chats" ||
|
||||
strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
|
||||
api.authenticate(http.HandlerFunc(api.chatRoutes)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.URL.Path {
|
||||
case "/health/live", "/health/ready":
|
||||
handleHealth(w, r)
|
||||
|
||||
case "/api/v1/users":
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
api.createUser(w, r)
|
||||
|
||||
case "/api/v1/users/me":
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
api.authenticate(http.HandlerFunc(api.currentUser)).ServeHTTP(w, r)
|
||||
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
}
|
||||
}
|
||||
|
||||
func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool {
|
||||
if r.Method == method {
|
||||
return true
|
||||
}
|
||||
|
||||
w.Header().Set("Allow", method)
|
||||
writeError(
|
||||
w,
|
||||
http.StatusMethodNotAllowed,
|
||||
"invalid_request",
|
||||
"Method not allowed",
|
||||
)
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
func sessionError(w http.ResponseWriter, err error, basic bool) {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if basic {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Invalid credentials")
|
||||
return
|
||||
}
|
||||
writeAppError(w, err)
|
||||
}
|
||||
|
||||
func loginSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions) {
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
username, secret, ok := r.BasicAuth()
|
||||
if !ok || len(r.Header.Values("Authorization")) != 1 {
|
||||
sessionError(w, service.ErrUnauthorized, true)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
result, err := sessions.Login(r.Context(), username, secret)
|
||||
if err != nil {
|
||||
sessionError(w, err, true)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusCreated, result)
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, error) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
fields := strings.Fields(r.Header.Get("Authorization"))
|
||||
if len(fields) != 2 || !strings.EqualFold(fields[0], "Bearer") {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
return fields[1], nil
|
||||
}
|
||||
|
||||
func currentSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions, logout bool) {
|
||||
method := http.MethodGet
|
||||
if logout {
|
||||
method = http.MethodDelete
|
||||
}
|
||||
if !requireMethod(w, r, method) {
|
||||
return
|
||||
}
|
||||
token, err := bearerToken(r)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
if logout {
|
||||
if err := sessions.Logout(r.Context(), token); err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
user, err := sessions.CurrentUser(r.Context(), token)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package httpapi
|
||||
|
||||
import "net/http"
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
func (api *API) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body createUserRequest
|
||||
|
||||
if !readJSON(w, r, &body, "username", "display_name") {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := api.messenger.RegisterUser(body.Username, body.DisplayName)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (api *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user := userFromContext(r.Context())
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func newAPI() http.Handler {
|
||||
return httpapi.NewHandler(
|
||||
service.NewMessenger(store.NewMemoryStore()),
|
||||
)
|
||||
}
|
||||
|
||||
func request(
|
||||
handler http.Handler,
|
||||
method string,
|
||||
path string,
|
||||
body string,
|
||||
userID string,
|
||||
) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
if userID != "" {
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
}
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
func checkError(
|
||||
t *testing.T,
|
||||
response *httptest.ResponseRecorder,
|
||||
status int,
|
||||
code string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if response.Code != status {
|
||||
t.Fatalf(
|
||||
"status: got %d, want %d; body=%s",
|
||||
response.Code, status, response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode error response: %v", err)
|
||||
}
|
||||
|
||||
if body.Error.Code != code {
|
||||
t.Errorf("error code: got %q, want %q", body.Error.Code, code)
|
||||
}
|
||||
|
||||
id := response.Header().Get("X-Request-Id")
|
||||
if id == "" || body.Error.RequestID != id {
|
||||
t.Error("missing or mismatched request ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserHTTPFlow(t *testing.T) {
|
||||
handler := newAPI()
|
||||
|
||||
body := `{"username":"alice","display_name":"Алиса 👋"}`
|
||||
|
||||
created := request(handler, http.MethodPost, "/api/v1/users", body, "")
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("registration: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
|
||||
if created.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("registration response has no request ID")
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if user.ID == "" || user.CreatedAt.IsZero() ||
|
||||
user.Username != "alice" || user.DisplayName != "Алиса 👋" {
|
||||
t.Fatalf("invalid user: %+v", user)
|
||||
}
|
||||
|
||||
me := request(handler, http.MethodGet, "/api/v1/users/me", "", user.ID)
|
||||
if me.Code != http.StatusOK {
|
||||
t.Fatalf("current user: %d %s", me.Code, me.Body.String())
|
||||
}
|
||||
|
||||
var current model.User
|
||||
if err := json.Unmarshal(me.Body.Bytes(), ¤t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if current != user {
|
||||
t.Fatalf("current user differs: %+v", current)
|
||||
}
|
||||
|
||||
duplicate := request(handler, http.MethodPost, "/api/v1/users", body, "")
|
||||
checkError(t, duplicate, http.StatusConflict, "conflict")
|
||||
|
||||
for _, id := range []string{
|
||||
"",
|
||||
"invalid",
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
} {
|
||||
response := request(
|
||||
handler, http.MethodGet, "/api/v1/users/me", "", id,
|
||||
)
|
||||
checkError(t, response, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationInvalidJSON(t *testing.T) {
|
||||
cases := []string{
|
||||
``,
|
||||
`{`,
|
||||
`null`,
|
||||
`[]`,
|
||||
`{}`,
|
||||
`{"username":"alice"}`,
|
||||
`{"username":null,"display_name":"Alice"}`,
|
||||
`{"username":123,"display_name":"Alice"}`,
|
||||
`{"username":"alice","display_name":"Alice","extra":true}`,
|
||||
`{"username":"alice","display_name":"Alice"} {}`,
|
||||
`{"username":"Alice","display_name":"Alice"}`,
|
||||
`{"username":"alice","display_name":" "}`,
|
||||
}
|
||||
|
||||
for _, body := range cases {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
response := request(
|
||||
newAPI(), http.MethodPost, "/api/v1/users", body, "",
|
||||
)
|
||||
checkError(t, response, http.StatusBadRequest, "invalid_request")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationContentType(t *testing.T) {
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/users",
|
||||
strings.NewReader(`{"username":"alice","display_name":"Alice"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
newAPI().ServeHTTP(response, req)
|
||||
|
||||
checkError(
|
||||
t, response,
|
||||
http.StatusUnsupportedMediaType, "unsupported_media_type",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memoryKiB uint32 = 64 * 1024
|
||||
iterations uint32 = 3
|
||||
parallelism uint8 = 4
|
||||
saltLength = 16
|
||||
keyLength uint32 = 32
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidPassword = errors.New("password must contain 12 to 128 UTF-8 code points and a non-whitespace character")
|
||||
ErrInvalidHash = errors.New("invalid or unsupported password hash")
|
||||
encoding = base64.RawStdEncoding.Strict()
|
||||
profile = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$",
|
||||
argon2.Version, memoryKiB, iterations, parallelism)
|
||||
)
|
||||
|
||||
func Validate(value string) error {
|
||||
if !utf8.ValidString(value) {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
length := utf8.RuneCountInString(value)
|
||||
if length < 12 || length > 128 || strings.TrimSpace(value) == "" {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Hash(value string) (string, error) {
|
||||
if err := Validate(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
salt := make([]byte, saltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
|
||||
return profile + encoding.EncodeToString(salt) + "$" + encoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func Verify(value, encoded string) (bool, error) {
|
||||
if len(encoded) != len(profile)+encoding.EncodedLen(saltLength)+1+encoding.EncodedLen(int(keyLength)) ||
|
||||
!strings.HasPrefix(encoded, profile) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(encoded, profile), "$")
|
||||
if len(parts) != 2 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
salt, err := encoding.DecodeString(parts[0])
|
||||
if err != nil || len(salt) != saltLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expected, err := encoding.DecodeString(parts[1])
|
||||
if err != nil || len(expected) != int(keyLength) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
if err := Validate(value); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
actual := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{"empty", "", false},
|
||||
{"11 characters", strings.Repeat("a", 11), false},
|
||||
{"12 characters", strings.Repeat("a", 12), true},
|
||||
{"128 Unicode characters", strings.Repeat("я", 128), true},
|
||||
{"129 Unicode characters", strings.Repeat("я", 129), false},
|
||||
{"invalid UTF-8", strings.Repeat("a", 12) + string([]byte{0xff}), false},
|
||||
{"only spaces", strings.Repeat(" ", 12), false},
|
||||
{"only Unicode whitespace", strings.Repeat("\u00a0\u2003\t\n", 3), false},
|
||||
{"spaces preserved", " пароль:секрет ", true},
|
||||
{"colon allowed", "пароль:секрет", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := Validate(tc.value)
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("valid=%v, error=%v", tc.valid, err)
|
||||
}
|
||||
if !tc.valid {
|
||||
if _, err := Hash(tc.value); !errors.Is(err, ErrInvalidPassword) {
|
||||
t.Fatalf("Hash error=%v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashAndVerify(t *testing.T) {
|
||||
value := " пароль:секрет "
|
||||
first, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("independent salts produced identical records")
|
||||
}
|
||||
for _, encoded := range []string{first, second} {
|
||||
ok, err := Verify(value, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("correct password: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
for _, wrong := range []string{"другой:пароль", strings.TrimSpace(value), "short"} {
|
||||
ok, err := Verify(wrong, first)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("wrong password: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongUnicodePasswordIsNotTruncated(t *testing.T) {
|
||||
value := strings.Repeat("я", 128)
|
||||
encoded, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ok, err := Verify(value, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("match=%v error=%v", ok, err)
|
||||
}
|
||||
ok, err = Verify(strings.Repeat("я", 127)+"ю", encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("last character ignored: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
encoded := profile + encoding.EncodeToString(make([]byte, saltLength)) + "$" + encoding.EncodeToString(make([]byte, keyLength))
|
||||
for _, broken := range []string{
|
||||
"", "plaintext", encoded[:len(encoded)-1], encoded + "$extra",
|
||||
strings.Replace(encoded, "v=19", "v=18", 1),
|
||||
strings.Replace(encoded, "m=65536", "m=999999999", 1),
|
||||
strings.Replace(encoded, "t=3", "t=0", 1),
|
||||
strings.Replace(encoded, "p=4", "p=0", 1),
|
||||
profile + "!" + encoded[len(profile)+1:],
|
||||
} {
|
||||
ok, err := Verify("пароль:секрет", broken)
|
||||
if ok || !errors.Is(err, ErrInvalidHash) {
|
||||
t.Fatalf("match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) &&
|
||||
strings.TrimSpace(value) != "" &&
|
||||
utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateChat(
|
||||
actorID string,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (model.Chat, error) {
|
||||
if !validText(title, 100) ||
|
||||
len(memberIDs) < 1 ||
|
||||
len(memberIDs) > 100 {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
normalized := make([]string, len(memberIDs))
|
||||
|
||||
for i, id := range memberIDs {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
normalized[i] = strings.ToLower(id)
|
||||
}
|
||||
|
||||
return m.store.CreateChat(actorID, title, normalized)
|
||||
}
|
||||
|
||||
func (m *Messenger) GetChat(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) (model.Chat, error) {
|
||||
if !uuidPattern.MatchString(chatID) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.GetChat(actorID, strings.ToLower(chatID))
|
||||
}
|
||||
|
||||
func (m *Messenger) ListChats(
|
||||
actorID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (Page[model.Chat], error) {
|
||||
chats := m.store.ListChats(actorID)
|
||||
|
||||
return paginate(
|
||||
chats,
|
||||
"chats:"+actorID,
|
||||
limit,
|
||||
cursor,
|
||||
func(chat model.Chat) position {
|
||||
return position{CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateMessage(
|
||||
actorID string,
|
||||
chatID string,
|
||||
text string,
|
||||
) (model.Message, error) {
|
||||
chat, err := m.GetChat(actorID, chatID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if !validText(text, 4000) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.CreateMessage(actorID, chat.ID, text)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListMessages(
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (Page[model.Message], error) {
|
||||
if !uuidPattern.MatchString(chatID) {
|
||||
return Page[model.Message]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
chatID = strings.ToLower(chatID)
|
||||
|
||||
messages, err := m.store.ListMessages(actorID, chatID)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
|
||||
return paginate(
|
||||
messages,
|
||||
"messages:"+chatID,
|
||||
limit,
|
||||
cursor,
|
||||
func(message model.Message) position {
|
||||
return position{CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIdempotencyKeyValidation(t *testing.T) {
|
||||
for _, key := range []string{"a", "retry-1._:ABC09", strings.Repeat("a", 128)} {
|
||||
if !idempotencyKeyPattern.MatchString(key) {
|
||||
t.Fatalf("valid key rejected: %q", key)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"", " ", "a b", "ключ", "a\n", strings.Repeat("a", 129)} {
|
||||
// Nil DB ensures invalid input is rejected before any storage call.
|
||||
m := NewPersistentMessenger(nil)
|
||||
_, err := m.CreateMessage(context.Background(), "actor",
|
||||
"12345678-1234-4234-8234-123456789abc", "hello", key)
|
||||
if !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("key %q: got %v, want invalid request", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
var (
|
||||
usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
uuidPattern = regexp.MustCompile(
|
||||
`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`,
|
||||
)
|
||||
)
|
||||
|
||||
type Messenger struct {
|
||||
store *store.MemoryStore
|
||||
}
|
||||
|
||||
func NewMessenger(memory *store.MemoryStore) *Messenger {
|
||||
return &Messenger{
|
||||
store: memory,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messenger) RegisterUser(
|
||||
username string,
|
||||
displayName string,
|
||||
) (model.User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if !utf8.ValidString(displayName) {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(displayName)
|
||||
|
||||
if length < 1 || length > 100 {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.CreateUser(username, displayName)
|
||||
}
|
||||
|
||||
func (m *Messenger) CurrentUser(id string) (model.User, error) {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
|
||||
user, err := m.store.GetUser(strings.ToLower(id))
|
||||
|
||||
if errors.Is(err, store.ErrUserNotFound) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package service_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func TestRegisterUserValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
username string
|
||||
displayName string
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
name: "valid Unicode name",
|
||||
username: "alice_01",
|
||||
displayName: "Алиса 👋",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "100 Unicode code points",
|
||||
username: "alice",
|
||||
displayName: strings.Repeat("👋", 100),
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "101 Unicode code points",
|
||||
username: "alice",
|
||||
displayName: strings.Repeat("👋", 101),
|
||||
},
|
||||
{
|
||||
name: "short username",
|
||||
username: "ab",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "long username",
|
||||
username: strings.Repeat("a", 33),
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "uppercase username",
|
||||
username: "Alice",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "non ASCII username",
|
||||
username: "алиса",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "empty display name",
|
||||
username: "alice",
|
||||
displayName: "",
|
||||
},
|
||||
{
|
||||
name: "whitespace display name",
|
||||
username: "alice",
|
||||
displayName: " \t\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
user, err := m.RegisterUser(tt.username, tt.displayName)
|
||||
|
||||
if !tt.valid {
|
||||
if !errors.Is(err, service.ErrInvalidRequest) {
|
||||
t.Fatalf("expected ErrInvalidRequest, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterUser: %v", err)
|
||||
}
|
||||
|
||||
if user.Username != tt.username ||
|
||||
user.DisplayName != tt.displayName {
|
||||
t.Fatalf("user fields changed: %+v", user)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterDuplicateUsername(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
if _, err := m.RegisterUser("alice", "Алиса"); err != nil {
|
||||
t.Fatalf("first registration: %v", err)
|
||||
}
|
||||
|
||||
_, err := m.RegisterUser("alice", "Другое имя")
|
||||
if !errors.Is(err, store.ErrUsernameTaken) {
|
||||
t.Fatalf("expected ErrUsernameTaken, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUser(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
created, err := m.RegisterUser("alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterUser: %v", err)
|
||||
}
|
||||
|
||||
for _, id := range []string{
|
||||
created.ID,
|
||||
strings.ToUpper(created.ID),
|
||||
} {
|
||||
found, err := m.CurrentUser(id)
|
||||
if err != nil {
|
||||
t.Fatalf("CurrentUser(%q): %v", id, err)
|
||||
}
|
||||
|
||||
if found != created {
|
||||
t.Fatalf("got %+v, want %+v", found, created)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range []string{
|
||||
"",
|
||||
"not-a-uuid",
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
} {
|
||||
_, err := m.CurrentUser(id)
|
||||
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Errorf(
|
||||
"CurrentUser(%q): expected ErrUnauthorized, got %v",
|
||||
id,
|
||||
err,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type position struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type cursorData struct {
|
||||
Scope string `json:"scope"`
|
||||
After position `json:"after"`
|
||||
}
|
||||
|
||||
func less(a, b position) bool {
|
||||
if a.CreatedAt.Equal(b.CreatedAt) {
|
||||
return a.ID < b.ID
|
||||
}
|
||||
return a.CreatedAt.Before(b.CreatedAt)
|
||||
}
|
||||
|
||||
func paginate[T any](
|
||||
items []T,
|
||||
scope string,
|
||||
limit int,
|
||||
cursor string,
|
||||
key func(T) position,
|
||||
) (Page[T], error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
var after *position
|
||||
|
||||
if cursor != "" {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
var decoded cursorData
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if decoded.Scope != scope ||
|
||||
decoded.After.CreatedAt.IsZero() ||
|
||||
!uuidPattern.MatchString(decoded.After.ID) {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
after = &decoded.After
|
||||
}
|
||||
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return less(key(items[i]), key(items[j]))
|
||||
})
|
||||
|
||||
start := 0
|
||||
|
||||
if after != nil {
|
||||
start = sort.Search(len(items), func(i int) bool {
|
||||
return less(*after, key(items[i]))
|
||||
})
|
||||
}
|
||||
|
||||
end := min(start+limit, len(items))
|
||||
|
||||
page := Page[T]{
|
||||
Items: make([]T, end-start),
|
||||
}
|
||||
copy(page.Items, items[start:end])
|
||||
|
||||
if end < len(items) {
|
||||
raw, err := json.Marshal(cursorData{
|
||||
Scope: scope,
|
||||
After: key(items[end-1]),
|
||||
})
|
||||
if err != nil {
|
||||
return Page[T]{}, err
|
||||
}
|
||||
|
||||
next := base64.RawURLEncoding.EncodeToString(raw)
|
||||
page.NextCursor = &next
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PersistentMessenger struct{ db *store.PostgresStore }
|
||||
|
||||
func NewPersistentMessenger(db *store.PostgresStore) *PersistentMessenger {
|
||||
return &PersistentMessenger{db: db}
|
||||
}
|
||||
|
||||
func (m *PersistentMessenger) CreateChat(ctx context.Context, actor, title string, members []string) (model.Chat, error) {
|
||||
if !validText(title, 100) || len(members) < 1 || len(members) > 100 {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
normalized := make([]string, len(members))
|
||||
seen := make(map[string]bool)
|
||||
for i, id := range members {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
id = strings.ToLower(id)
|
||||
if seen[id] {
|
||||
return model.Chat{}, store.ErrInvalidMembers
|
||||
}
|
||||
seen[id] = true
|
||||
normalized[i] = id
|
||||
}
|
||||
if !seen[actor] {
|
||||
return model.Chat{}, store.ErrInvalidMembers
|
||||
}
|
||||
return m.db.CreateChat(ctx, title, normalized)
|
||||
}
|
||||
func (m *PersistentMessenger) GetChat(ctx context.Context, actor, id string) (model.Chat, error) {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
return m.db.GetChat(ctx, actor, strings.ToLower(id))
|
||||
}
|
||||
func decodePosition(cursor, scope string, limit int) (*store.Position, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if cursor == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if len(cursor) > 2048 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
var data cursorData
|
||||
if json.Unmarshal(raw, &data) != nil || data.Scope != scope || data.After.CreatedAt.IsZero() || !uuidPattern.MatchString(data.After.ID) {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if data.After.CreatedAt.Year() < 1 || data.After.CreatedAt.Year() > 9999 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return &store.Position{CreatedAt: data.After.CreatedAt, ID: strings.ToLower(data.After.ID)}, nil
|
||||
}
|
||||
func databasePage[T any](items []T, limit int, scope string, key func(T) position) (Page[T], error) {
|
||||
page := Page[T]{Items: items}
|
||||
if len(items) <= limit {
|
||||
return page, nil
|
||||
}
|
||||
page.Items = items[:limit]
|
||||
raw, err := json.Marshal(cursorData{Scope: scope, After: key(page.Items[limit-1])})
|
||||
if err != nil {
|
||||
return Page[T]{}, err
|
||||
}
|
||||
cursor := base64.RawURLEncoding.EncodeToString(raw)
|
||||
page.NextCursor = &cursor
|
||||
return page, nil
|
||||
}
|
||||
func (m *PersistentMessenger) ListChats(ctx context.Context, actor string, limit int, cursor string) (Page[model.Chat], error) {
|
||||
scope := "chats:" + actor
|
||||
after, err := decodePosition(cursor, scope, limit)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
items, err := m.db.ChatPage(ctx, actor, limit+1, after)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
return databasePage(items, limit, scope, func(c model.Chat) position { return position{CreatedAt: c.CreatedAt, ID: c.ID} })
|
||||
}
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (m *PersistentMessenger) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) {
|
||||
if !uuidPattern.MatchString(chatID) || !validText(text, 4000) || !idempotencyKeyPattern.MatchString(key) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
return m.db.CreateMessage(ctx, actor, strings.ToLower(chatID), text, key)
|
||||
}
|
||||
func (m *PersistentMessenger) ListMessages(ctx context.Context, actor, chatID string, limit int, cursor string) (Page[model.Message], error) {
|
||||
chat, err := m.GetChat(ctx, actor, chatID)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
scope := "messages:" + chat.ID
|
||||
after, err := decodePosition(cursor, scope, limit)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
items, err := m.db.MessagePage(ctx, chat.ID, limit+1, after)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
return databasePage(items, limit, scope, func(message model.Message) position { return position{CreatedAt: message.CreatedAt, ID: message.ID} })
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type UserWriter interface {
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
}
|
||||
|
||||
type Registration struct {
|
||||
users UserWriter
|
||||
hashSlots chan struct{}
|
||||
}
|
||||
|
||||
func NewRegistration(users UserWriter) *Registration {
|
||||
return &Registration{users: users, hashSlots: make(chan struct{}, 2)}
|
||||
}
|
||||
|
||||
func (s *Registration) Register(ctx context.Context, username, displayName, secret string) (model.User, error) {
|
||||
if !usernamePattern.MatchString(username) || !validText(displayName, 100) || password.Validate(secret) != nil {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
select {
|
||||
case s.hashSlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
hash, err := password.Hash(secret)
|
||||
<-s.hashSlots
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
return s.users.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type registrationWriter struct {
|
||||
calls int
|
||||
hash string
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *registrationWriter) CreateUser(_ context.Context, username, displayName, hash string) (model.User, error) {
|
||||
w.calls++
|
||||
w.hash = hash
|
||||
return model.User{Username: username, DisplayName: displayName}, w.err
|
||||
}
|
||||
|
||||
func TestRegistrationHashesBeforeStorage(t *testing.T) {
|
||||
w := ®istrationWriter{}
|
||||
s := NewRegistration(w)
|
||||
user, err := s.Register(context.Background(), "alice", "Алиса", "учебный:пароль")
|
||||
if err != nil || user.Username != "alice" || w.calls != 1 {
|
||||
t.Fatalf("registration failed: %v", err)
|
||||
}
|
||||
ok, err := password.Verify("учебный:пароль", w.hash)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("stored value is not a valid password hash: %v", err)
|
||||
}
|
||||
w.err = store.ErrUsernameTaken
|
||||
_, err = s.Register(context.Background(), "alice", "Алиса", "учебный:пароль")
|
||||
if !errors.Is(err, store.ErrUsernameTaken) {
|
||||
t.Fatalf("conflict lost: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationRejectsBeforeStorage(t *testing.T) {
|
||||
w := ®istrationWriter{}
|
||||
s := NewRegistration(w)
|
||||
for _, fields := range [][3]string{{"Alice", "Алиса", "учебный:пароль"}, {"alice", " ", "учебный:пароль"}, {"alice", "Алиса", "short"}} {
|
||||
_, err := s.Register(context.Background(), fields[0], fields[1], fields[2])
|
||||
if !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("invalid input accepted: %v", err)
|
||||
}
|
||||
}
|
||||
if w.calls != 0 {
|
||||
t.Fatal("invalid data reached storage")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type SessionStore interface {
|
||||
Credentials(context.Context, string) (model.User, string, error)
|
||||
CreateSession(context.Context, []byte, string, int64) (time.Time, error)
|
||||
SessionUser(context.Context, []byte) (model.User, error)
|
||||
DeleteSession(context.Context, []byte) error
|
||||
}
|
||||
|
||||
type Sessions struct {
|
||||
db SessionStore
|
||||
ttl int64
|
||||
hashSlots chan struct{}
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
func NewSessions(db SessionStore, registration *Registration, ttl int64) (*Sessions, error) {
|
||||
if ttl < 1 || ttl > 31536000 {
|
||||
return nil, errors.New("SESSION_TTL_SECONDS must be between 1 and 31536000")
|
||||
}
|
||||
dummy, err := password.Hash("dummy-password-for-missing-user")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Sessions{db: db, ttl: ttl, hashSlots: registration.hashSlots, dummyHash: dummy}, nil
|
||||
}
|
||||
|
||||
func (s *Sessions) Login(ctx context.Context, username, secret string) (SessionResponse, error) {
|
||||
if !usernamePattern.MatchString(username) || password.Validate(secret) != nil {
|
||||
return SessionResponse{}, ErrUnauthorized
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
user, hash, err := s.db.Credentials(ctx, username)
|
||||
missing := errors.Is(err, store.ErrUserNotFound)
|
||||
if err != nil && !missing {
|
||||
return SessionResponse{}, err
|
||||
}
|
||||
if missing {
|
||||
hash = s.dummyHash
|
||||
}
|
||||
select {
|
||||
case s.hashSlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return SessionResponse{}, store.ErrUnavailable
|
||||
}
|
||||
matches, err := password.Verify(secret, hash)
|
||||
<-s.hashSlots
|
||||
if err != nil {
|
||||
return SessionResponse{}, errors.New("stored password hash is invalid")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return SessionResponse{}, store.ErrUnavailable
|
||||
}
|
||||
if missing || !matches {
|
||||
return SessionResponse{}, ErrUnauthorized
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return SessionResponse{}, errors.New("cannot generate session token")
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
expires, err := s.db.CreateSession(ctx, digest[:], user.ID, s.ttl)
|
||||
if err != nil {
|
||||
return SessionResponse{}, err
|
||||
}
|
||||
return SessionResponse{Token: token, TokenType: "Bearer", ExpiresAt: expires, User: user}, nil
|
||||
}
|
||||
|
||||
func tokenDigest(token string) ([]byte, error) {
|
||||
if len(token) != 43 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
||||
if err != nil || len(raw) != 32 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
return digest[:], nil
|
||||
}
|
||||
|
||||
func (s *Sessions) CurrentUser(ctx context.Context, token string) (model.User, error) {
|
||||
digest, err := tokenDigest(token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
user, err := s.db.SessionUser(ctx, digest)
|
||||
if errors.Is(err, store.ErrSessionNotFound) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *Sessions) Logout(ctx context.Context, token string) error {
|
||||
digest, err := tokenDigest(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.db.DeleteSession(ctx, digest)
|
||||
if errors.Is(err, store.ErrSessionNotFound) {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type sessionFake struct {
|
||||
hash string
|
||||
stored []byte
|
||||
writes int
|
||||
unavailable bool
|
||||
}
|
||||
|
||||
func (f *sessionFake) Credentials(_ context.Context, username string) (model.User, string, error) {
|
||||
if f.unavailable {
|
||||
return model.User{}, "", store.ErrUnavailable
|
||||
}
|
||||
if username != "alice" {
|
||||
return model.User{}, "", store.ErrUserNotFound
|
||||
}
|
||||
return model.User{ID: "user-id", Username: username}, f.hash, nil
|
||||
}
|
||||
func (f *sessionFake) CreateSession(_ context.Context, hash []byte, _ string, _ int64) (time.Time, error) {
|
||||
f.writes++
|
||||
f.stored = append([]byte(nil), hash...)
|
||||
return time.Now().UTC().Add(time.Hour), nil
|
||||
}
|
||||
func (f *sessionFake) SessionUser(_ context.Context, hash []byte) (model.User, error) {
|
||||
if f.unavailable {
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
if string(hash) != string(f.stored) || f.stored == nil {
|
||||
return model.User{}, store.ErrSessionNotFound
|
||||
}
|
||||
return model.User{ID: "user-id", Username: "alice"}, nil
|
||||
}
|
||||
func (f *sessionFake) DeleteSession(_ context.Context, hash []byte) error {
|
||||
if _, err := f.SessionUser(context.Background(), hash); err != nil {
|
||||
return err
|
||||
}
|
||||
f.stored = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
hash, err := password.Hash("учебный:пароль")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := &sessionFake{hash: hash}
|
||||
s, err := NewSessions(db, NewRegistration(nil), 3600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, username := range []string{"alice", "missing"} {
|
||||
if _, err := s.Login(context.Background(), username, "неверный:пароль"); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("bad credentials: %v", err)
|
||||
}
|
||||
}
|
||||
if db.writes != 0 {
|
||||
t.Fatal("invalid login created a session")
|
||||
}
|
||||
session, err := s.Login(context.Background(), "alice", "учебный:пароль")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256([]byte(session.Token))
|
||||
if len(session.Token) != 43 || string(db.stored) != string(digest[:]) {
|
||||
t.Fatal("must store digest of random token")
|
||||
}
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.unavailable = true
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, store.ErrUnavailable) {
|
||||
t.Fatalf("outage: %v", err)
|
||||
}
|
||||
db.unavailable = false
|
||||
if err := s.Logout(context.Background(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("revoked: %v", err)
|
||||
}
|
||||
if err := s.Logout(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("repeated logout: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("resource not found")
|
||||
ErrInvalidMembers = errors.New("invalid chat members")
|
||||
)
|
||||
|
||||
func cloneChat(chat model.Chat) model.Chat {
|
||||
chat.MemberIDs = slices.Clone(chat.MemberIDs)
|
||||
return chat
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateChat(
|
||||
actorID string,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (model.Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
if _, exists := s.usersByID[id]; !exists {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
}
|
||||
|
||||
if !seen[actorID] {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
for {
|
||||
if _, exists := s.chatsByID[id]; !exists {
|
||||
break
|
||||
}
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: slices.Clone(memberIDs),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.chatsByID[id] = chat
|
||||
s.messagesByChat[id] = []model.Message{}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChat(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) (model.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListChats(actorID string) []model.Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]model.Chat, 0)
|
||||
|
||||
for _, chat := range s.chatsByID {
|
||||
if slices.Contains(chat.MemberIDs, actorID) {
|
||||
result = append(result, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
actorID string,
|
||||
chatID string,
|
||||
text string,
|
||||
) (model.Message, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
history := s.messagesByChat[chatID]
|
||||
|
||||
for slices.ContainsFunc(history, func(message model.Message) bool {
|
||||
return message.ID == id
|
||||
}) {
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
|
||||
createdAt := time.Now().UTC()
|
||||
|
||||
if len(history) > 0 {
|
||||
last := history[len(history)-1].CreatedAt
|
||||
if !createdAt.After(last) {
|
||||
createdAt = last.Add(time.Nanosecond)
|
||||
}
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: actorID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChat[chatID] = append(history, message)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListMessages(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) ([]model.Message, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
result := make([]model.Message, len(s.messagesByChat[chatID]))
|
||||
copy(result, s.messagesByChat[chatID])
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username already exists")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
usersByID map[string]model.User
|
||||
userIDsByName map[string]string
|
||||
chatsByID map[string]model.Chat
|
||||
messagesByChat map[string][]model.Message
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
usersByID: make(map[string]model.User),
|
||||
userIDsByName: make(map[string]string),
|
||||
chatsByID: make(map[string]model.Chat),
|
||||
messagesByChat: make(map[string][]model.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateUser(
|
||||
username string,
|
||||
displayName string,
|
||||
) (model.User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, exists := s.userIDsByName[username]; exists {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("generate user ID: %w", err)
|
||||
}
|
||||
|
||||
for {
|
||||
if _, exists := s.usersByID[id]; !exists {
|
||||
break
|
||||
}
|
||||
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("generate user ID: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.userIDsByName[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUser(id string) (model.User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, exists := s.usersByID[id]
|
||||
if !exists {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func newUUID() (string, error) {
|
||||
var value [16]byte
|
||||
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
value[6] = (value[6] & 0x0f) | 0x40
|
||||
value[8] = (value[8] & 0x3f) | 0x80
|
||||
|
||||
return fmt.Sprintf(
|
||||
"%x-%x-%x-%x-%x",
|
||||
value[0:4],
|
||||
value[4:6],
|
||||
value[6:8],
|
||||
value[8:10],
|
||||
value[10:16],
|
||||
), nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func TestCreateAndGetUser(t *testing.T) {
|
||||
s := store.NewMemoryStore()
|
||||
|
||||
created, err := s.CreateUser("alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
if created.ID == "" {
|
||||
t.Fatal("user ID is empty")
|
||||
}
|
||||
|
||||
if created.CreatedAt.IsZero() {
|
||||
t.Fatal("creation time is empty")
|
||||
}
|
||||
|
||||
found, err := s.GetUser(created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser: %v", err)
|
||||
}
|
||||
|
||||
if found != created {
|
||||
t.Fatalf("stored user differs: got %+v, want %+v", found, created)
|
||||
}
|
||||
|
||||
_, err = s.GetUser("00000000-0000-4000-8000-000000000000")
|
||||
if !errors.Is(err, store.ErrUserNotFound) {
|
||||
t.Fatalf("expected ErrUserNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentDuplicateUsername(t *testing.T) {
|
||||
s := store.NewMemoryStore()
|
||||
|
||||
const clients = 10
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, clients)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < clients; i++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
<-start
|
||||
_, err := s.CreateUser("alice", "Алиса")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if created != 1 || conflicts != clients-1 {
|
||||
t.Fatalf(
|
||||
"expected 1 creation and %d conflicts; got %d creations and %d conflicts",
|
||||
clients-1,
|
||||
created,
|
||||
conflicts,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func OpenPostgres(ctx context.Context, passwordFile string) (*pgxpool.Pool, error) {
|
||||
password, err := os.ReadFile(passwordFile)
|
||||
if err != nil {
|
||||
return nil, errors.New("cannot read PostgreSQL password file")
|
||||
}
|
||||
secret := strings.TrimRight(string(password), "\r\n")
|
||||
if secret == "" {
|
||||
return nil, errors.New("PostgreSQL password file is empty")
|
||||
}
|
||||
|
||||
config, err := pgxpool.ParseConfig(
|
||||
"host=postgres port=5432 dbname=messenger user=messenger sslmode=disable",
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid PostgreSQL configuration")
|
||||
}
|
||||
config.ConnConfig.Password = secret
|
||||
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = "3000"
|
||||
config.ConnConfig.RuntimeParams["lock_timeout"] = "2000"
|
||||
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2"
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 0
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(connectCtx, config)
|
||||
if err != nil {
|
||||
return nil, errors.New("cannot create PostgreSQL pool")
|
||||
}
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, errors.New("PostgreSQL connection check failed")
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateChat(ctx context.Context, title string, members []string) (model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
chat := model.Chat{ID: id, Title: title, MemberIDs: members}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, id, title).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
for _, member := range members {
|
||||
_, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, id, member)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && (pgErr.Code == "23503" || pgErr.Code == "23505") {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
|
||||
|
||||
func (s *PostgresStore) GetChat(ctx context.Context, actor, id string) (model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(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, actor).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ChatPage(ctx context.Context, actor string, limit int, after *Position) ([]model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
query := `SELECT ` + chatColumns + ` FROM chats c WHERE EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)`
|
||||
args := []any{actor, limit}
|
||||
if after != nil {
|
||||
query += ` AND (c.created_at,c.id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at,c.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Chat, 0)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
items = append(items, chat)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key already used for another message")
|
||||
|
||||
func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT c.id::text FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2) FOR UPDATE OF c`, chatID, actor).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
var message model.Message
|
||||
|
||||
err = tx.QueryRow(ctx, `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at
|
||||
FROM message_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 AND k.expires_at>clock_timestamp()`,
|
||||
actor, chatID, key).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
|
||||
if err == nil {
|
||||
if message.Text != text {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
message.CreatedAt = message.CreatedAt.UTC()
|
||||
return message, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
VALUES($1,$2,$3,$4,GREATEST(clock_timestamp(),
|
||||
COALESCE((SELECT created_at + INTERVAL '1 microsecond' FROM messages WHERE chat_id=$2 ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp())))
|
||||
RETURNING id::text,chat_id::text,sender_id::text,text,created_at`, id, chatID, actor, text).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO message_keys(user_id,chat_id,key,message_id,expires_at)
|
||||
VALUES($1,$2,$3,$4,clock_timestamp()+INTERVAL '24 hours')
|
||||
ON CONFLICT(user_id,chat_id,key) DO UPDATE
|
||||
SET message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at`, actor, chatID, key, message.ID)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
message.CreatedAt = message.CreatedAt.UTC()
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit int, after *Position) ([]model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1`
|
||||
args := []any{chatID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (created_at,id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY messages.created_at,messages.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Message, 0)
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found")
|
||||
|
||||
func (s *PostgresStore) Credentials(ctx context.Context, username string) (model.User, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at, password_hash FROM users WHERE username=$1`, username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, hash, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateSession(ctx context.Context, hash []byte, userID string, ttlSeconds int64) (time.Time, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var expires time.Time
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, CURRENT_TIMESTAMP + $3::bigint * INTERVAL '1 second') RETURNING expires_at`, hash, userID, ttlSeconds).Scan(&expires)
|
||||
if err != nil {
|
||||
return time.Time{}, ErrUnavailable
|
||||
}
|
||||
return expires.UTC(), nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) SessionUser(ctx context.Context, hash []byte) (model.User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var userID string
|
||||
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id::text FROM sessions
|
||||
WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
return s.profile(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteSession(ctx context.Context, hash []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
type ProfileCache interface {
|
||||
Get(context.Context, string) (model.User, bool)
|
||||
Set(context.Context, model.User)
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
profiles ProfileCache
|
||||
}
|
||||
|
||||
func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore {
|
||||
return &PostgresStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) WithProfiles(profiles ProfileCache) *PostgresStore {
|
||||
s.profiles = profiles
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *PostgresStore) profile(ctx context.Context, id string) (model.User, error) {
|
||||
if s.profiles != nil {
|
||||
if user, ok := s.profiles.Get(ctx, id); ok {
|
||||
return user, nil
|
||||
}
|
||||
}
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at FROM users WHERE id=$1`, id).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
if s.profiles != nil {
|
||||
s.profiles.Set(ctx, user)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, errors.New("cannot generate user ID")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id::text, username, display_name, created_at`,
|
||||
id, username, displayName, passwordHash,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key" {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user