feat: moved code from lab3
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func createChatHandler(chats *services.ChatService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||
return
|
||||
}
|
||||
var request createChatRequest
|
||||
if err := decodeJSONBody(r, &request); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := chats.Create(r.Context(), userID, request.Title, request.MemberIDs)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, chat)
|
||||
}
|
||||
}
|
||||
|
||||
func getChatHandler(chats *services.ChatService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
if chatID == "" || strings.Contains(chatID, "/") {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, chat)
|
||||
}
|
||||
}
|
||||
|
||||
func listChatsHandler(chats *services.ChatService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := pageParams(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := chats.List(r.Context(), userID, limit, cursor)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, page)
|
||||
}
|
||||
}
|
||||
|
||||
func chatCollectionHandler(chats *services.ChatService) http.HandlerFunc {
|
||||
create := createChatHandler(chats)
|
||||
list := listChatsHandler(chats)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
list(w, r)
|
||||
} else {
|
||||
create(w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||
get := getChatHandler(chats)
|
||||
createMessage := createMessageHandler(chats, messages)
|
||||
listMessages := listMessagesHandler(chats, messages)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/messages") {
|
||||
if r.Method == http.MethodGet {
|
||||
listMessages(w, r)
|
||||
} else {
|
||||
createMessage(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
get(w, r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
type apiError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
type errorResponse struct {
|
||||
Error apiError `json:"error"`
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "request-id-generation-failed"
|
||||
}
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
response := errorResponse{Error: apiError{Code: code, Message: message, RequestID: requestID}}
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
log.Printf("failed to encode error response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeServiceError(w http.ResponseWriter, err error, requestID string) {
|
||||
var invalid services.InvalidInput
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
writeError(w, 400, "invalid_request", invalid.Message, requestID)
|
||||
case errors.Is(err, services.ErrConflict):
|
||||
writeError(w, 409, "conflict", "request conflicts with an existing resource", requestID)
|
||||
case errors.Is(err, services.ErrUnknownUser):
|
||||
writeError(w, 401, "unauthorized", "unknown user", requestID)
|
||||
case errors.Is(err, services.ErrChatNotFound):
|
||||
writeError(w, 404, "not_found", "chat not found", requestID)
|
||||
default:
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(value); err != nil {
|
||||
log.Printf("failed to encode response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func requestUserID(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) {
|
||||
id := currentUserID(r)
|
||||
if id == "" {
|
||||
writeError(w, 401, "unauthorized", "valid Bearer session is required", requestID)
|
||||
return "", false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func pageParams(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
|
||||
limit := 50
|
||||
if values, exists := r.URL.Query()["limit"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
writeError(w, 400, "invalid_request", "invalid limit", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
parsed, err := strconv.Atoi(values[0])
|
||||
if err != nil {
|
||||
writeError(w, 400, "invalid_request", "limit must be between 1 and 100", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
var cursor string
|
||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
writeError(w, 400, "invalid_request", "invalid cursor", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
return limit, cursor, true
|
||||
}
|
||||
|
||||
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, healthResponse{"ok"})
|
||||
}
|
||||
|
||||
func readyHandler(health *services.HealthService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
// Readiness must finish before HAProxy's one-second check read timeout.
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := health.Ready(ctx); err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, healthResponse{"ok"})
|
||||
}
|
||||
}
|
||||
|
||||
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health/live", healthHandler)
|
||||
mux.HandleFunc("/health/ready", readyHandler(health))
|
||||
mux.Handle("/api/v1/users", createUserHandler(users))
|
||||
mux.Handle("/api/v1/auth/sessions", sessionHandler(sessions))
|
||||
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
|
||||
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users)))
|
||||
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
|
||||
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages)))
|
||||
return withInstance(mux)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Docker's hostname lets the operator map an API response to its container.
|
||||
var instanceID = func() string {
|
||||
id, err := os.Hostname()
|
||||
if err != nil || id == "" {
|
||||
return uuid.NewString()
|
||||
}
|
||||
return id
|
||||
}()
|
||||
|
||||
var draining atomic.Bool
|
||||
|
||||
func BeginShutdown() { draining.Store(true) }
|
||||
|
||||
func withInstance(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", instanceID)
|
||||
w.Header().Set("X-Request-Id", newRequestID())
|
||||
if draining.Load() && r.URL.Path != "/health/live" {
|
||||
writeError(w, 503, "unavailable", "instance is shutting down", w.Header().Get("X-Request-Id"))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs json.RawMessage `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func messageChatID(path string) (string, bool) {
|
||||
const prefix = "/api/v1/chats/"
|
||||
const suffix = "/messages"
|
||||
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
|
||||
return "", false
|
||||
}
|
||||
chatID := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
|
||||
if chatID == "" || strings.Contains(chatID, "/") {
|
||||
return "", false
|
||||
}
|
||||
return chatID, true
|
||||
}
|
||||
|
||||
func createMessageHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID, ok := messageChatID(r.URL.Path)
|
||||
if !ok {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||
return
|
||||
}
|
||||
var request createMessageRequest
|
||||
if err := decodeJSONBody(r, &request); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||
return
|
||||
}
|
||||
if len(request.AttachmentIDs) > 0 {
|
||||
var ids []string
|
||||
if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil || len(ids) != 0 {
|
||||
writeError(w, 400, "invalid_request", "attachments are not supported in lab3; use an empty array or omit attachment_ids", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
keys := r.Header.Values("Idempotency-Key")
|
||||
if len(keys) != 1 {
|
||||
writeError(w, 400, "invalid_request", "exactly one Idempotency-Key is required", requestID)
|
||||
return
|
||||
}
|
||||
message, err := messages.CreateIdempotent(r.Context(), userID, chat, request.Text, keys[0])
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, message)
|
||||
}
|
||||
}
|
||||
|
||||
func listMessagesHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID, ok := messageChatID(r.URL.Path)
|
||||
if !ok {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||
return
|
||||
}
|
||||
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := pageParams(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := messages.List(r.Context(), userID, chat, limit, cursor)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type authenticatedUserKey struct{}
|
||||
|
||||
func currentUserID(r *http.Request) string {
|
||||
id, _ := r.Context().Value(authenticatedUserKey{}).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
func authRequired(sessions *services.SessionService, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" {
|
||||
unauthorized(w, "Bearer", newRequestID())
|
||||
return
|
||||
}
|
||||
user, err := sessions.User(r.Context(), strings.TrimPrefix(authorization, "Bearer "))
|
||||
if errors.Is(err, services.ErrInvalidSession) {
|
||||
unauthorized(w, "Bearer", newRequestID())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID)))
|
||||
})
|
||||
}
|
||||
|
||||
func unauthorized(w http.ResponseWriter, scheme, requestID string) {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if scheme == "Basic" {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
} else {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
writeError(w, 401, "unauthorized", "invalid credentials", requestID)
|
||||
}
|
||||
|
||||
func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || r.ContentLength > 0 {
|
||||
unauthorized(w, "Basic", requestID)
|
||||
return
|
||||
}
|
||||
user, token, expires, valid, err := sessions.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if !valid {
|
||||
unauthorized(w, "Basic", requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User any `json:"user"`
|
||||
}{token, "Bearer", expires, user})
|
||||
}
|
||||
}
|
||||
|
||||
func logoutHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodDelete {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if err := sessions.Revoke(r.Context(), token); err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeJSONBody(r *http.Request, destination any) error {
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
var body json.RawMessage
|
||||
if err := decoder.Decode(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("more than one JSON value")
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
if fields == nil {
|
||||
return fmt.Errorf("JSON body must be an object")
|
||||
}
|
||||
// encoding/json matches struct fields case-insensitively, even with
|
||||
// DisallowUnknownFields. Check exact contract names before decoding values.
|
||||
typeOfRequest := reflect.TypeOf(destination).Elem()
|
||||
allowed := make(map[string]bool, typeOfRequest.NumField())
|
||||
for i := 0; i < typeOfRequest.NumField(); i++ {
|
||||
name := strings.Split(typeOfRequest.Field(i).Tag.Get("json"), ",")[0]
|
||||
if name != "" && name != "-" {
|
||||
allowed[name] = true
|
||||
}
|
||||
}
|
||||
for name := range fields {
|
||||
if !allowed[name] {
|
||||
return fmt.Errorf("unknown JSON field %q", name)
|
||||
}
|
||||
}
|
||||
return json.Unmarshal(body, destination)
|
||||
}
|
||||
|
||||
func createUserHandler(users *services.UserService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||
return
|
||||
}
|
||||
var request createUserRequest
|
||||
if err := decodeJSONBody(r, &request); err != nil {
|
||||
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||
return
|
||||
}
|
||||
user, err := users.Create(r.Context(), request.Username, request.DisplayName, request.Password)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, user)
|
||||
}
|
||||
}
|
||||
|
||||
func currentUserHandler(users *services.UserService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
userID, ok := requestUserID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
user, err := users.Get(r.Context(), userID)
|
||||
if err != nil {
|
||||
writeServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, user)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func serverAddress() string {
|
||||
host := os.Getenv("APP_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
|
||||
return net.JoinHostPort(host, port)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if environment := os.Getenv("APP_ENV"); environment != "" {
|
||||
log.SetPrefix("[" + environment + "] ")
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
response, err := client.Get("http://" + net.JoinHostPort("127.0.0.1", port) + "/health/ready")
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") {
|
||||
log.Fatal("usage: messenger migrate up|down")
|
||||
}
|
||||
url, err := repositories.DatabaseURL()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err = repositories.RunMigrations(url, os.Args[2]); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("migration %s complete", os.Args[2])
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
db, err := repositories.OpenDatabase(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Fatalf("database initialization failed: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
// Opt-in experiment telemetry goes to container logs, never a public port.
|
||||
if os.Getenv("BENCH_POOL_STATS") == "1" {
|
||||
go func() {
|
||||
for range time.Tick(time.Second) {
|
||||
s := db.Stat()
|
||||
data, _ := json.Marshal(map[string]any{
|
||||
"time": time.Now().UTC(), "acquired": s.AcquiredConns(),
|
||||
"total": s.TotalConns(), "max": s.MaxConns(),
|
||||
"gomaxprocs": runtime.GOMAXPROCS(0), "goroutines": runtime.NumGoroutine(),
|
||||
"acquire_count": s.AcquireCount(), "acquire_duration_ns": s.AcquireDuration().Nanoseconds(),
|
||||
"empty_acquire_count": s.EmptyAcquireCount(), "canceled_acquire_count": s.CanceledAcquireCount(),
|
||||
})
|
||||
log.Printf("benchmark_pool %s", data)
|
||||
}
|
||||
}()
|
||||
}
|
||||
redisClient, err := repositories.RedisClientFromEnvironment()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer redisClient.Close()
|
||||
sessionStore := repositories.NewSessionStore(redisClient, "messenger:session:")
|
||||
userStore := repositories.NewUserStore(db)
|
||||
chatStore := repositories.NewChatStore(db)
|
||||
idempotencyTTL, err := repositories.IdempotencyTTL()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
messageStore := repositories.NewMessageStoreWithTTL(db, idempotencyTTL)
|
||||
ttl, err := services.SessionTTL()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
userService := services.NewUserService(userStore)
|
||||
sessionService := services.NewSessionService(userService, sessionStore, ttl)
|
||||
chatService := services.NewChatService(chatStore)
|
||||
messageService := services.NewMessageService(messageStore)
|
||||
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessionService, chatService, messageService)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: serverAddress(),
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
shutdownContext, stop := signal.NotifyContext(
|
||||
context.Background(),
|
||||
os.Interrupt,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
defer stop()
|
||||
|
||||
serverErrors := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Printf("server is listening on %s", server.Addr)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
serverErrors <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErrors:
|
||||
log.Printf("server error: %v", err)
|
||||
|
||||
case <-shutdownContext.Done():
|
||||
log.Printf("shutdown signal received")
|
||||
handlers.BeginShutdown()
|
||||
|
||||
shutdownDeadline, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
10*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownDeadline); err != nil {
|
||||
log.Printf("graceful shutdown failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("server stopped gracefully")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatStore(db *pgxpool.Pool) *ChatStore {
|
||||
return &ChatStore{db: db}
|
||||
}
|
||||
|
||||
var ErrUnknownMember = errors.New("unknown member")
|
||||
|
||||
func (s *ChatStore) Create(ctx context.Context, title string, memberIDs []string) (Chat, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
membersCopy := append([]string(nil), memberIDs...)
|
||||
chat := Chat{
|
||||
ID: uuid.New().String(),
|
||||
Title: title,
|
||||
MemberIDs: membersCopy,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
for _, id := range membersCopy {
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE id=$1)", id).Scan(&exists); err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
if !exists {
|
||||
return Chat{}, ErrUnknownMember
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
for _, id := range membersCopy {
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id); err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetByID(ctx context.Context, id string) (Chat, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var chat Chat
|
||||
err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt)
|
||||
if err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
rows, err := s.db.Query(ctx, "SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", id)
|
||||
if err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
chat.MemberIDs = []string{}
|
||||
for rows.Next() {
|
||||
var member string
|
||||
if err = rows.Scan(&member); err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
chat.MemberIDs = append(chat.MemberIDs, member)
|
||||
}
|
||||
return chat, rows.Err()
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListPageForUser(ctx context.Context, userID string, cursor *ChatCursor, limit int) ([]Chat, bool, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
afterTime := time.Time{}
|
||||
afterID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != nil {
|
||||
afterTime = cursor.CreatedAt
|
||||
afterID = cursor.ChatID
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=$1 AND (c.created_at,c.id)>($2,$3::uuid) ORDER BY c.created_at,c.id LIMIT $4`, userID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := []Chat{}
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err = rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
more := len(chats) > limit
|
||||
if more {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
for i := range chats {
|
||||
chat, err := s.GetByID(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
chats[i] = chat
|
||||
}
|
||||
return chats, more, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func RedisClientFromEnvironment() (*redis.Client, error) {
|
||||
if path := os.Getenv("CACHE_URL_FILE"); path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options, err := redis.ParseURL(strings.TrimSpace(string(data)))
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid Redis URL in CACHE_URL_FILE")
|
||||
}
|
||||
options.PoolSize = 10
|
||||
options.MaxRetries = -1
|
||||
options.DialTimeout = time.Second
|
||||
options.ReadTimeout = time.Second
|
||||
options.WriteTimeout = time.Second
|
||||
return redis.NewClient(options), nil
|
||||
}
|
||||
address := os.Getenv("REDIS_ADDR")
|
||||
if address == "" {
|
||||
address = "redis:6379"
|
||||
}
|
||||
return NewRedisClient(address), nil
|
||||
}
|
||||
|
||||
func IdempotencyTTL() (time.Duration, error) {
|
||||
value := os.Getenv("IDEMPOTENCY_TTL_SECONDS")
|
||||
if value == "" {
|
||||
value = "86400"
|
||||
}
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds < 1 || seconds > 31536000 {
|
||||
return 0, errors.New("IDEMPOTENCY_TTL_SECONDS must be between 1 and 31536000")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package repositories
|
||||
|
||||
import "time"
|
||||
|
||||
type ChatCursor struct {
|
||||
UserID string `json:"user_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
|
||||
type MessageCursor struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
MessageID string `json:"message_id"`
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
func DatabaseURL() (string, error) {
|
||||
if path := os.Getenv("DATABASE_URL_FILE"); path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(data)), nil
|
||||
}
|
||||
if url := os.Getenv("DATABASE_URL"); url != "" {
|
||||
return url, nil
|
||||
}
|
||||
return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required")
|
||||
}
|
||||
|
||||
func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
url, err := DatabaseURL()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
if value := os.Getenv("DATABASE_MAX_CONNS"); value != "" {
|
||||
maxConns, parseErr := strconv.Atoi(value)
|
||||
if parseErr != nil || maxConns < 1 || maxConns > 100 {
|
||||
return nil, errors.New("DATABASE_MAX_CONNS must be between 1 and 100")
|
||||
}
|
||||
cfg.MaxConns = int32(maxConns)
|
||||
}
|
||||
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.Ping(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// RunMigrations uses versioned up/down SQL embedded in the API binary.
|
||||
// "down" rolls back exactly one version and is an explicit operator command.
|
||||
func RunMigrations(url, direction string) error {
|
||||
source, err := iofs.New(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sqlDB, err := sql.Open("pgx", url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
driver, err := pgxmigrate.WithInstance(sqlDB, &pgxmigrate.Config{})
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
return err
|
||||
}
|
||||
m, err := migrate.NewWithInstance("iofs", source, "pgx5", driver)
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
return err
|
||||
}
|
||||
defer m.Close()
|
||||
if direction == "down" {
|
||||
err = m.Steps(-1)
|
||||
} else {
|
||||
err = m.Up()
|
||||
}
|
||||
if errors.Is(err, migrate.ErrNoChange) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func NotFound(err error) bool {
|
||||
return errors.Is(err, pgx.ErrNoRows)
|
||||
}
|
||||
|
||||
func CheckViolation(err error) bool {
|
||||
var pgerr *pgconn.PgError
|
||||
return errors.As(err, &pgerr) && pgerr.Code == "23514"
|
||||
}
|
||||
|
||||
func UniqueViolation(err error) bool {
|
||||
var pgerr *pgconn.PgError
|
||||
return errors.As(err, &pgerr) && pgerr.Code == "23505"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type HealthStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewHealthStore(db *pgxpool.Pool) *HealthStore {
|
||||
return &HealthStore{db: db}
|
||||
}
|
||||
|
||||
func (s *HealthStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
return s.db.Ping(ctx)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message")
|
||||
|
||||
// CreateIdempotent commits the message and its replay record together.
|
||||
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string) (Message, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
// The transaction-scoped lock is shared by all API replicas. Hash collisions
|
||||
// only serialize unrelated requests; the full scope is checked by the query.
|
||||
scope := senderID + ":POST:/api/v1/chats/" + chatID + "/messages:" + key
|
||||
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
var message Message
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency i JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.sender_id=$1 AND i.chat_id=$2 AND i.key=$3
|
||||
AND i.expires_at > clock_timestamp()`, senderID, chatID, key).
|
||||
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
|
||||
if err == nil {
|
||||
message.CreatedAt = message.CreatedAt.UTC()
|
||||
if message.Text != text {
|
||||
return Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
return message, tx.Commit(ctx)
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, err
|
||||
}
|
||||
|
||||
// Expiry permits key reuse; it never deletes the original message.
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM message_idempotency WHERE sender_id=$1 AND chat_id=$2 AND key=$3", senderID, chatID, key); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
message = Message{
|
||||
ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, chatID, senderID, text, message.CreatedAt); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(sender_id,chat_id,key,message_id,expires_at)
|
||||
VALUES($1,$2,$3,$4,clock_timestamp() + $5 * interval '1 second')`, senderID, chatID, key, message.ID, s.idempotencyTTL.Seconds()); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
return message, tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type MessageStore struct {
|
||||
db *pgxpool.Pool
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageStore(db *pgxpool.Pool) *MessageStore {
|
||||
return NewMessageStoreWithTTL(db, 24*time.Hour)
|
||||
}
|
||||
|
||||
func NewMessageStoreWithTTL(db *pgxpool.Pool, ttl time.Duration) *MessageStore {
|
||||
return &MessageStore{db: db, idempotencyTTL: ttl}
|
||||
}
|
||||
|
||||
func (s *MessageStore) Create(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (Message, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
message := Message{
|
||||
ID: uuid.New().String(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
_, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
|
||||
return message, err
|
||||
}
|
||||
|
||||
func (s *MessageStore) ListPageByChat(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
cursor *MessageCursor,
|
||||
limit int,
|
||||
) ([]Message, bool, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
afterTime := time.Time{}
|
||||
afterID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != nil {
|
||||
afterTime = cursor.CreatedAt
|
||||
afterID = cursor.MessageID
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
more := len(items) > limit
|
||||
if more {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, more, nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,32 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash bytea NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id,chat_id);
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expires_at);
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE sessions;
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE message_idempotency;
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE message_idempotency (
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key varchar(128) NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (sender_id, chat_id, key)
|
||||
);
|
||||
@@ -0,0 +1,56 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found")
|
||||
|
||||
type SessionStore struct {
|
||||
client *redis.Client
|
||||
prefix string
|
||||
}
|
||||
|
||||
func NewRedisClient(address string) *redis.Client {
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: address, PoolSize: 10, MaxRetries: -1,
|
||||
DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second,
|
||||
})
|
||||
}
|
||||
|
||||
func NewSessionStore(client *redis.Client, prefix string) *SessionStore {
|
||||
return &SessionStore{client: client, prefix: prefix}
|
||||
}
|
||||
|
||||
func (s *SessionStore) key(tokenHash []byte) string {
|
||||
return s.prefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error {
|
||||
ttl := time.Until(expires)
|
||||
if ttl <= 0 {
|
||||
return errors.New("session expiry must be in the future")
|
||||
}
|
||||
return s.client.Set(ctx, s.key(tokenHash), userID, ttl).Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) UserID(ctx context.Context, tokenHash []byte) (string, error) {
|
||||
id, err := s.client.Get(ctx, s.key(tokenHash)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrSessionNotFound
|
||||
}
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
||||
return s.client.Del(ctx, s.key(tokenHash)).Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) Ping(ctx context.Context) error {
|
||||
return s.client.Ping(ctx).Err()
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
const queryTimeout = 5 * time.Second
|
||||
|
||||
func boundedQuery(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type UserStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserStore(db *pgxpool.Pool) *UserStore {
|
||||
return &UserStore{db: db}
|
||||
}
|
||||
|
||||
func (s *UserStore) Create(ctx context.Context, username, displayName string, passwordHash []byte) (User, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
user := User{
|
||||
ID: uuid.New().String(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
_, err := s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserStore) GetByID(ctx context.Context, id string) (User, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var user User
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserStore) GetCredentials(ctx context.Context, username string) (User, []byte, error) {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
var user User
|
||||
var packedHash []byte
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return User{}, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, nil, err
|
||||
}
|
||||
return user, packedHash, nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ChatPage struct {
|
||||
Items []repositories.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ChatService struct {
|
||||
chats *repositories.ChatStore
|
||||
}
|
||||
|
||||
func NewChatService(chats *repositories.ChatStore) *ChatService {
|
||||
return &ChatService{chats: chats}
|
||||
}
|
||||
|
||||
func ChatHasMember(chat repositories.Chat, userID string) bool {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, currentUserID, title string, memberIDs []string) (repositories.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return repositories.Chat{}, InvalidInput{"title must not be blank"}
|
||||
}
|
||||
if utf8.RuneCountInString(title) > 100 {
|
||||
return repositories.Chat{}, InvalidInput{"title is too long"}
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must contain from 1 to 100 users"}
|
||||
}
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
normalizedMembers := make([]string, len(memberIDs))
|
||||
for i, memberID := range memberIDs {
|
||||
parsed, err := uuid.Parse(memberID)
|
||||
if err != nil {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must contain valid UUIDs"}
|
||||
}
|
||||
memberID = parsed.String()
|
||||
if _, exists := seen[memberID]; exists {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must not contain duplicates"}
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
normalizedMembers[i] = memberID
|
||||
}
|
||||
if _, exists := seen[currentUserID]; !exists {
|
||||
return repositories.Chat{}, InvalidInput{"current user must be a chat member"}
|
||||
}
|
||||
chat, err := s.chats.Create(ctx, title, normalizedMembers)
|
||||
if errors.Is(err, repositories.ErrUnknownMember) {
|
||||
return repositories.Chat{}, InvalidInput{"all members must be existing users"}
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, currentUserID, chatID string) (repositories.Chat, error) {
|
||||
chat, err := s.chats.GetByID(ctx, chatID)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.Chat{}, err
|
||||
}
|
||||
if !ChatHasMember(chat, currentUserID) {
|
||||
return repositories.Chat{}, ErrChatNotFound
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func EncodeChatCursor(cursor repositories.ChatCursor) (string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func DecodeChatCursor(value string) (repositories.ChatCursor, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
var cursor repositories.ChatCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
if cursor.UserID == "" || cursor.ChatID == "" || cursor.CreatedAt.IsZero() {
|
||||
return repositories.ChatCursor{}, strconv.ErrSyntax
|
||||
}
|
||||
if _, err := uuid.Parse(cursor.UserID); err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
if _, err := uuid.Parse(cursor.ChatID); err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursorToken string) (ChatPage, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return ChatPage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||
}
|
||||
var cursor *repositories.ChatCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := DecodeChatCursor(cursorToken)
|
||||
if err != nil || decoded.UserID != userID {
|
||||
return ChatPage{}, InvalidInput{"invalid cursor"}
|
||||
}
|
||||
cursor = &decoded
|
||||
}
|
||||
items, more, err := s.chats.ListPageForUser(ctx, userID, cursor, limit)
|
||||
if err != nil {
|
||||
return ChatPage{}, err
|
||||
}
|
||||
page := ChatPage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = []repositories.Chat{}
|
||||
}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
next, err := EncodeChatCursor(repositories.ChatCursor{UserID: userID, CreatedAt: last.CreatedAt, ChatID: last.ID})
|
||||
if err != nil {
|
||||
return ChatPage{}, err
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package services
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnknownUser = errors.New("unknown user")
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrInvalidSession = errors.New("invalid session")
|
||||
)
|
||||
|
||||
type InvalidInput struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e InvalidInput) Error() string { return e.Message }
|
||||
@@ -0,0 +1,23 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type HealthService struct {
|
||||
health *repositories.HealthStore
|
||||
sessions *repositories.SessionStore
|
||||
}
|
||||
|
||||
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore) *HealthService {
|
||||
return &HealthService{health: health, sessions: sessions}
|
||||
}
|
||||
|
||||
func (s *HealthService) Ready(ctx context.Context) error {
|
||||
if err := s.health.Ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.sessions.Ping(ctx)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string) (repositories.Message, error) {
|
||||
if !ChatHasMember(chat, userID) {
|
||||
return repositories.Message{}, ErrChatNotFound
|
||||
}
|
||||
if !idempotencyKeyPattern.MatchString(key) {
|
||||
return repositories.Message{}, InvalidInput{"Idempotency-Key must contain 1-128 ASCII letters, digits or ._:-"}
|
||||
}
|
||||
if strings.TrimSpace(text) == "" || utf8.RuneCountInString(text) > 4000 {
|
||||
return repositories.Message{}, InvalidInput{"text must contain 1-4000 characters and must not be blank"}
|
||||
}
|
||||
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key)
|
||||
if errors.Is(err, repositories.ErrIdempotencyConflict) {
|
||||
return repositories.Message{}, ErrConflict
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type MessagePage struct {
|
||||
Items []repositories.Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type MessageService struct {
|
||||
messages *repositories.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageService(messages *repositories.MessageStore) *MessageService {
|
||||
return &MessageService{messages: messages}
|
||||
}
|
||||
|
||||
func EncodeMessageCursor(cursor repositories.MessageCursor) (string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func DecodeMessageCursor(value string) (repositories.MessageCursor, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
var cursor repositories.MessageCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
if cursor.ChatID == "" || cursor.MessageID == "" || cursor.CreatedAt.IsZero() {
|
||||
return repositories.MessageCursor{}, strconv.ErrSyntax
|
||||
}
|
||||
if _, err := uuid.Parse(cursor.ChatID); err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
if _, err := uuid.Parse(cursor.MessageID); err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, userID string, chat repositories.Chat, limit int, cursorToken string) (MessagePage, error) {
|
||||
if !ChatHasMember(chat, userID) {
|
||||
return MessagePage{}, ErrChatNotFound
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return MessagePage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||
}
|
||||
var cursor *repositories.MessageCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := DecodeMessageCursor(cursorToken)
|
||||
if err != nil || decoded.ChatID != chat.ID {
|
||||
return MessagePage{}, InvalidInput{"invalid cursor"}
|
||||
}
|
||||
cursor = &decoded
|
||||
}
|
||||
items, more, err := s.messages.ListPageByChat(ctx, chat.ID, cursor, limit)
|
||||
if err != nil {
|
||||
return MessagePage{}, err
|
||||
}
|
||||
page := MessagePage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = []repositories.Message{}
|
||||
}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
next, err := EncodeMessageCursor(repositories.MessageCursor{ChatID: chat.ID, CreatedAt: last.CreatedAt, MessageID: last.ID})
|
||||
if err != nil {
|
||||
return MessagePage{}, err
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory uint32 = 64 * 1024
|
||||
argonIterations uint32 = 3
|
||||
argonParallelism uint8 = 2
|
||||
passwordSaltSize = 16
|
||||
passwordHashSize = 32
|
||||
)
|
||||
|
||||
// HashPassword stores the salt and Argon2id parameters in one PHC-encoded value.
|
||||
func HashPassword(password string) ([]byte, error) {
|
||||
salt := make([]byte, passwordSaltSize)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, passwordHashSize)
|
||||
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
)
|
||||
return []byte(encoded), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password string, encoded []byte) (bool, error) {
|
||||
parts := strings.Split(string(encoded), "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return false, errors.New("invalid password hash format")
|
||||
}
|
||||
var memory, iterations uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil ||
|
||||
fmt.Sprintf("m=%d,t=%d,p=%d", memory, iterations, parallelism) != parts[3] ||
|
||||
memory < 8*1024 || memory > 128*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 8 {
|
||||
return false, errors.New("invalid password hash parameters")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil || len(salt) != passwordSaltSize {
|
||||
return false, errors.New("invalid password salt")
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil || len(expected) != passwordHashSize {
|
||||
return false, errors.New("invalid password hash")
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, passwordHashSize)
|
||||
return subtle.ConstantTimeCompare(expected, actual) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
users *UserService
|
||||
sessions *repositories.SessionStore
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func SessionTTL() (time.Duration, error) {
|
||||
value := os.Getenv("SESSION_TTL_SECONDS")
|
||||
if value == "" {
|
||||
return time.Hour, nil
|
||||
}
|
||||
seconds, err := strconv.Atoi(value)
|
||||
if err != nil || seconds < 1 || seconds > 31536000 {
|
||||
return 0, errors.New("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
|
||||
func NewSessionService(users *UserService, sessions *repositories.SessionStore, ttl time.Duration) *SessionService {
|
||||
return &SessionService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *SessionService) Login(ctx context.Context, username, password string) (repositories.User, string, time.Time, bool, error) {
|
||||
user, valid, err := s.users.Authenticate(ctx, username, password)
|
||||
if err != nil || !valid {
|
||||
return repositories.User{}, "", time.Time{}, valid, err
|
||||
}
|
||||
token, expires, err := s.CreateForUser(ctx, user.ID)
|
||||
if err != nil {
|
||||
return repositories.User{}, "", time.Time{}, false, err
|
||||
}
|
||||
return user, token, expires, true, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateForUser(ctx context.Context, userID string) (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := hex.EncodeToString(raw)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
if err := s.sessions.Create(ctx, hash[:], userID, expires); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) User(ctx context.Context, token string) (repositories.User, error) {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
id, err := s.sessions.UserID(ctx, hash[:])
|
||||
if errors.Is(err, repositories.ErrSessionNotFound) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.User{}, err
|
||||
}
|
||||
user, err := s.users.Get(ctx, id)
|
||||
if errors.Is(err, ErrUnknownUser) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *SessionService) Revoke(ctx context.Context, token string) error {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return s.sessions.Revoke(ctx, hash[:])
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserService struct {
|
||||
users *repositories.UserStore
|
||||
}
|
||||
|
||||
func NewUserService(users *repositories.UserStore) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (repositories.User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return repositories.User{}, InvalidInput{"username must contain 3-32 lowercase latin letters, digits or underscores"}
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return repositories.User{}, InvalidInput{"display_name must not be blank"}
|
||||
}
|
||||
if utf8.RuneCountInString(displayName) > 100 {
|
||||
return repositories.User{}, InvalidInput{"display_name is too long"}
|
||||
}
|
||||
if strings.TrimSpace(password) == "" || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||
return repositories.User{}, InvalidInput{"password must contain 12-128 characters"}
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return repositories.User{}, err
|
||||
}
|
||||
user, err := s.users.Create(ctx, username, displayName, hash)
|
||||
if repositories.UniqueViolation(err) {
|
||||
return repositories.User{}, ErrConflict
|
||||
}
|
||||
if repositories.CheckViolation(err) {
|
||||
return repositories.User{}, InvalidInput{"invalid user fields"}
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserService) Get(ctx context.Context, id string) (repositories.User, error) {
|
||||
user, err := s.users.GetByID(ctx, id)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.User{}, ErrUnknownUser
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserService) Authenticate(ctx context.Context, username, password string) (repositories.User, bool, error) {
|
||||
if !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
user, packedHash, err := s.users.GetCredentials(ctx, username)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
if err != nil || packedHash == nil {
|
||||
return repositories.User{}, false, err
|
||||
}
|
||||
valid, err := VerifyPassword(password, packedHash)
|
||||
if err != nil {
|
||||
return repositories.User{}, false, err
|
||||
}
|
||||
return user, valid, nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"messenger/src/backend/repositories"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConcurrentMessageCreation(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
userStore, chatStore := fixture.users, fixture.chats
|
||||
|
||||
const clientsCount = 10
|
||||
const messagesPerClient = 10
|
||||
const expectedMessages = clientsCount * messagesPerClient
|
||||
|
||||
memberIDs := make([]string, 0, clientsCount)
|
||||
users := make([]User, 0, clientsCount)
|
||||
|
||||
for i := range clientsCount {
|
||||
user, created := createTestUser(t, userStore,
|
||||
"user"+strconv.Itoa(i),
|
||||
"Пользователь "+strconv.Itoa(i),
|
||||
)
|
||||
|
||||
if !created {
|
||||
t.Fatalf("failed to create test user %d", i)
|
||||
}
|
||||
|
||||
users = append(users, user)
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat := createTestChat(t, chatStore,
|
||||
"Конкурентный чат",
|
||||
memberIDs,
|
||||
)
|
||||
|
||||
server := httptest.NewServer(fixture.router)
|
||||
defer server.Close()
|
||||
|
||||
client := server.Client()
|
||||
tokens := make([]string, clientsCount)
|
||||
for i, user := range users {
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
authorizeTestRequest(t, fixture, request, user.ID)
|
||||
tokens[i] = request.Header.Get("Authorization")
|
||||
}
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
messageIDs := make(chan string, expectedMessages)
|
||||
errors := make(chan error, expectedMessages)
|
||||
|
||||
for clientIndex := range clientsCount {
|
||||
waitGroup.Add(1)
|
||||
|
||||
go func(index int) {
|
||||
defer waitGroup.Done()
|
||||
|
||||
for messageIndex := range messagesPerClient {
|
||||
body := fmt.Appendf(nil,
|
||||
`{"text":"client-%d message-%d"}`,
|
||||
index,
|
||||
messageIndex,
|
||||
)
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
server.URL+"/api/v1/chats/"+chat.ID+"/messages",
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: create request: %w",
|
||||
index,
|
||||
err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Authorization", tokens[index])
|
||||
request.Header.Set("Idempotency-Key", fmt.Sprintf("client-%d-message-%d", index, messageIndex))
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: send request: %w",
|
||||
index,
|
||||
err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
responseBody, readErr := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
|
||||
if readErr != nil {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: read response: %w",
|
||||
index,
|
||||
readErr,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: expected status %d, got %d; body: %s",
|
||||
index,
|
||||
http.StatusCreated,
|
||||
response.StatusCode,
|
||||
string(responseBody),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
var message repositories.Message
|
||||
|
||||
if err := json.Unmarshal(responseBody, &message); err != nil {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: decode response: %w",
|
||||
index,
|
||||
err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if message.ID == "" {
|
||||
errors <- fmt.Errorf(
|
||||
"client %d: response contains empty message ID",
|
||||
index,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
messageIDs <- message.ID
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
|
||||
waitGroup.Wait()
|
||||
|
||||
close(errors)
|
||||
close(messageIDs)
|
||||
|
||||
for err := range errors {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
createdIDs := make(map[string]bool)
|
||||
|
||||
for messageID := range messageIDs {
|
||||
if createdIDs[messageID] {
|
||||
t.Fatalf("duplicate message ID returned: %s", messageID)
|
||||
}
|
||||
|
||||
createdIDs[messageID] = true
|
||||
}
|
||||
|
||||
if len(createdIDs) != expectedMessages {
|
||||
t.Fatalf(
|
||||
"expected %d unique created messages, got %d",
|
||||
expectedMessages,
|
||||
len(createdIDs),
|
||||
)
|
||||
}
|
||||
|
||||
// Дополнительно проверяем историю через HTTP API.
|
||||
request, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create history request: %v", err)
|
||||
}
|
||||
|
||||
request.Header.Set("Authorization", tokens[0])
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("request message history: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
|
||||
t.Fatalf(
|
||||
"expected history status %d, got %d; body: %s",
|
||||
http.StatusOK,
|
||||
response.StatusCode,
|
||||
string(body),
|
||||
)
|
||||
}
|
||||
|
||||
var page messagePage
|
||||
|
||||
if err := json.NewDecoder(response.Body).Decode(&page); err != nil {
|
||||
t.Fatalf("decode message history: %v", err)
|
||||
}
|
||||
|
||||
if len(page.Items) != expectedMessages {
|
||||
t.Fatalf(
|
||||
"expected %d messages in history, got %d",
|
||||
expectedMessages,
|
||||
len(page.Items),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
func TestConnectionFilesTakePrecedence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
database := filepath.Join(dir, "database")
|
||||
cache := filepath.Join(dir, "cache")
|
||||
if err := os.WriteFile(database, []byte("postgres://configured/db\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cache, []byte("redis://:test-password@configured:6380/3\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", database)
|
||||
t.Setenv("DATABASE_URL", "postgres://ignored/db")
|
||||
t.Setenv("CACHE_URL_FILE", cache)
|
||||
t.Setenv("REDIS_ADDR", "ignored:6379")
|
||||
url, err := repositories.DatabaseURL()
|
||||
if err != nil || url != "postgres://configured/db" {
|
||||
t.Fatalf("database file not used: %v", err)
|
||||
}
|
||||
client, err := repositories.RedisClientFromEnvironment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
options := client.Options()
|
||||
if options.Addr != "configured:6380" || options.DB != 3 || options.Password != "test-password" {
|
||||
t.Fatal("Redis URL settings not applied")
|
||||
}
|
||||
t.Setenv("CACHE_URL_FILE", filepath.Join(dir, "missing"))
|
||||
if _, err := repositories.RedisClientFromEnvironment(); err == nil {
|
||||
t.Fatal("missing file accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredIdempotencyTTL(t *testing.T) {
|
||||
t.Setenv("IDEMPOTENCY_TTL_SECONDS", "2")
|
||||
ttl, err := repositories.IdempotencyTTL()
|
||||
if err != nil || ttl != 2*time.Second {
|
||||
t.Fatalf("TTL not applied: %v", err)
|
||||
}
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
chat := createTestChat(t, f.chats, "Chat", []string{user.ID})
|
||||
store := repositories.NewMessageStoreWithTTL(f.db, ttl)
|
||||
ctx := context.Background()
|
||||
original, err := store.CreateIdempotent(ctx, chat.ID, user.ID, "hello", "ttl-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var remaining float64
|
||||
if err := f.db.QueryRow(ctx, "SELECT extract(epoch FROM expires_at-clock_timestamp()) FROM message_idempotency WHERE key='ttl-test'").Scan(&remaining); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if remaining <= 0 || remaining > 2 {
|
||||
t.Fatalf("unexpected remaining TTL: %f", remaining)
|
||||
}
|
||||
replay, err := store.CreateIdempotent(ctx, chat.ID, user.ID, "hello", "ttl-test")
|
||||
if err != nil || replay.ID != original.ID {
|
||||
t.Fatal("replay before expiry changed the message")
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, "UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE key='ttl-test'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reused, err := store.CreateIdempotent(ctx, chat.ID, user.ID, "hello", "ttl-test")
|
||||
if err != nil || reused.ID == original.ID {
|
||||
t.Fatal("expired key was not reusable")
|
||||
}
|
||||
if len(listTestMessages(t, store, chat.ID)) != 2 {
|
||||
t.Fatal("expiry removed an original message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidIdempotencyTTL(t *testing.T) {
|
||||
for _, value := range []string{"0", "-1", "abc", "31536001"} {
|
||||
t.Setenv("IDEMPOTENCY_TTL_SECONDS", value)
|
||||
if _, err := repositories.IdempotencyTTL(); err == nil {
|
||||
t.Fatalf("accepted TTL %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
func TestCursorRejectsInvalidUUIDBeforeDatabaseAccess(t *testing.T) {
|
||||
const userID = "11111111-1111-4111-8111-111111111111"
|
||||
const chatID = "22222222-2222-4222-8222-222222222222"
|
||||
const messageID = "33333333-3333-4333-8333-333333333333"
|
||||
createdAt := time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)
|
||||
for _, invalid := range []string{"not-a-uuid", "ffffffff-ffff-ffff-ffff-fffffffffffz"} {
|
||||
for _, field := range []string{"user_id", "chat_id"} {
|
||||
t.Run("chats/"+field+"/"+invalid, func(t *testing.T) {
|
||||
cursor := repositories.ChatCursor{UserID: userID, ChatID: chatID, CreatedAt: createdAt}
|
||||
if field == "user_id" {
|
||||
cursor.UserID = invalid
|
||||
} else {
|
||||
cursor.ChatID = invalid
|
||||
}
|
||||
token, err := services.EncodeChatCursor(cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := services.DecodeChatCursor(token); err == nil {
|
||||
t.Fatal("invalid UUID accepted")
|
||||
}
|
||||
// A nil store proves that validation finishes before any SQL call.
|
||||
_, err = services.NewChatService(nil).List(context.Background(), userID, 20, token)
|
||||
var invalidInput services.InvalidInput
|
||||
if !errors.As(err, &invalidInput) {
|
||||
t.Fatalf("want InvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, field := range []string{"chat_id", "message_id"} {
|
||||
t.Run("messages/"+field+"/"+invalid, func(t *testing.T) {
|
||||
cursor := repositories.MessageCursor{ChatID: chatID, MessageID: messageID, CreatedAt: createdAt}
|
||||
if field == "chat_id" {
|
||||
cursor.ChatID = invalid
|
||||
} else {
|
||||
cursor.MessageID = invalid
|
||||
}
|
||||
token, err := services.EncodeMessageCursor(cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := services.DecodeMessageCursor(token); err == nil {
|
||||
t.Fatal("invalid UUID accepted")
|
||||
}
|
||||
chat := repositories.Chat{ID: chatID, MemberIDs: []string{userID}}
|
||||
_, err = services.NewMessageService(nil).List(context.Background(), userID, chat, 20, token)
|
||||
var invalidInput services.InvalidInput
|
||||
if !errors.As(err, &invalidInput) {
|
||||
t.Fatalf("want InvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCursorPreservesPosition(t *testing.T) {
|
||||
original := repositories.ChatCursor{
|
||||
UserID: "11111111-1111-4111-8111-111111111111",
|
||||
ChatID: "22222222-2222-4222-8222-222222222222",
|
||||
CreatedAt: time.Date(2026, 10, 10, 12, 0, 0, 123000, time.UTC),
|
||||
}
|
||||
token, err := services.EncodeChatCursor(original)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := services.DecodeChatCursor(token)
|
||||
if err != nil || decoded != original {
|
||||
t.Fatalf("cursor changed: %+v, error: %v", decoded, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func TestConcurrentRegistrationSameUsername(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
const body = `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan int, 2)
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
results <- w.Code
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
counts := map[int]int{}
|
||||
for status := range results {
|
||||
counts[status]++
|
||||
}
|
||||
if counts[201] != 1 || counts[409] != 1 {
|
||||
t.Fatalf("registration statuses: %v", counts)
|
||||
}
|
||||
var users int
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM users WHERE username='alice'").Scan(&users); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if users != 1 {
|
||||
t.Fatalf("stored %d users with the same username", users)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTransactionRollsBackAfterMemberInsertFailure(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
alice, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
bob, _ := createTestUser(t, f.users, "bob", "Боб")
|
||||
_, err := f.db.Exec(context.Background(), `CREATE FUNCTION reject_bob() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.user_id = '`+bob.ID+`'::uuid THEN RAISE EXCEPTION 'forced member failure'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER reject_bob_insert BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION reject_bob();`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.chats.Create(context.Background(), "rollback-check", []string{alice.ID, bob.ID}); err == nil {
|
||||
t.Fatal("expected second member insertion to fail")
|
||||
}
|
||||
var chats, members int
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chats WHERE title='rollback-check'").Scan(&chats); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chat_members").Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 0 || members != 0 {
|
||||
t.Fatalf("transaction left chats=%d members=%d", chats, members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortSessionTTLAndLogout(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
t.Setenv("SESSION_TTL_SECONDS", "2")
|
||||
ttl, err := services.SessionTTL()
|
||||
if err != nil || ttl != 2*time.Second {
|
||||
t.Fatalf("short TTL: %v, %v", ttl, err)
|
||||
}
|
||||
sessions := services.NewSessionService(services.NewUserService(f.users), f.sessionStore, ttl)
|
||||
router := handlers.NewRouter(nil, services.NewUserService(f.users), sessions, nil, nil)
|
||||
assertHTTPUser := func(token string, want int) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("short TTL HTTP status: got %d, want %d", w.Code, want)
|
||||
}
|
||||
t.Logf("GET /api/v1/users/me: HTTP %d", w.Code)
|
||||
}
|
||||
token, _, err := sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := sessions.User(context.Background(), token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPUser(token, 200)
|
||||
expiryStarted := time.Now()
|
||||
expiryDeadline := expiryStarted.Add(5 * time.Second)
|
||||
for {
|
||||
_, err := sessions.User(context.Background(), token)
|
||||
if errors.Is(err, services.ErrInvalidSession) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("checking expiry: %v", err)
|
||||
}
|
||||
if time.Now().After(expiryDeadline) {
|
||||
t.Fatal("session with TTL=2 seconds did not expire within 5 seconds")
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Logf("SESSION_TTL_SECONDS=2: expiry observed after %s", time.Since(expiryStarted))
|
||||
assertHTTPUser(token, 401)
|
||||
token, _, err = f.sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.sessions.Revoke(context.Background(), token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.sessions.User(context.Background(), token); err != services.ErrInvalidSession {
|
||||
t.Fatalf("revoked token: %v", err)
|
||||
}
|
||||
assertHTTPUser(token, 401)
|
||||
}
|
||||
|
||||
func TestWrongPasswordAndLogoutHTTP(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
createTestUser(t, f.users, "alice", "Алиса")
|
||||
login := func(password string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("alice:"+password)))
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
if w := login("wrong-password"); w.Code != 401 {
|
||||
t.Fatalf("wrong password returned %d", w.Code)
|
||||
}
|
||||
missingUser := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
missingUser.SetBasicAuth("missing_user", "lab2-test-password")
|
||||
missingUserResponse := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(missingUserResponse, missingUser)
|
||||
if missingUserResponse.Code != 401 {
|
||||
t.Fatalf("unknown username returned %d", missingUserResponse.Code)
|
||||
}
|
||||
w := login("lab2-test-password")
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("valid login returned %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/chats/not-a-uuid/messages", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("invalid chat UUID returned %d", w.Code)
|
||||
}
|
||||
r = httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 204 {
|
||||
t.Fatalf("logout returned %d", w.Code)
|
||||
}
|
||||
r = httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+result.Token)
|
||||
w = httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != 401 {
|
||||
t.Fatalf("revoked token returned %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDependencyFailuresReturnUnavailable(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
failedRedis := repositories.NewRedisClient("127.0.0.1:1")
|
||||
defer failedRedis.Close()
|
||||
failedSessions := repositories.NewSessionStore(failedRedis, "unreachable:")
|
||||
redisRouter := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(f.db), failedSessions), services.NewUserService(f.users), services.NewSessionService(services.NewUserService(f.users), failedSessions, time.Hour), services.NewChatService(f.chats), services.NewMessageService(f.messages))
|
||||
assertStatus := func(router http.Handler, method, path, auth string, want int) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
if auth != "" {
|
||||
r.Header.Set("Authorization", auth)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("%s %s returned %d, want %d: %s", method, path, w.Code, want, w.Body.String())
|
||||
}
|
||||
}
|
||||
assertStatus(redisRouter, "GET", "/health/ready", "", 503)
|
||||
assertStatus(redisRouter, "GET", "/api/v1/users/me", "Bearer opaque-token", 503)
|
||||
assertStatus(redisRouter, "POST", "/api/v1/auth/sessions", "Basic "+base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password")), 503)
|
||||
|
||||
pool, err := pgxpool.New(context.Background(), os.Getenv("TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool.Close()
|
||||
userStore := repositories.NewUserStore(pool)
|
||||
dbRouter := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(pool), f.sessionStore), services.NewUserService(userStore), services.NewSessionService(services.NewUserService(userStore), f.sessionStore, time.Hour), services.NewChatService(repositories.NewChatStore(pool)), services.NewMessageService(repositories.NewMessageStore(pool)))
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertStatus(dbRouter, "GET", "/health/ready", "", 503)
|
||||
assertStatus(dbRouter, "GET", "/api/v1/users/me", "Bearer "+token, 503)
|
||||
assertStatus(dbRouter, "GET", "/api/v1/users/me", "", 401)
|
||||
}
|
||||
|
||||
func TestHistoryQueryPlanAtTenThousandMessages(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
chat := createTestChat(t, f.chats, "plan-check", []string{user.ID})
|
||||
ctx := context.Background()
|
||||
_, err := f.db.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(),$1,$2,'plan message','2026-01-01'::timestamptz + n * interval '1 microsecond'
|
||||
FROM generate_series(1,10000) AS n`, chat.ID, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.db.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var lateTime time.Time
|
||||
var lateID string
|
||||
if err := f.db.QueryRow(ctx, "SELECT created_at,id FROM messages WHERE chat_id=$1 ORDER BY created_at,id OFFSET 9000 LIMIT 1", chat.ID).Scan(&lateTime, &lateID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
at time.Time
|
||||
id string
|
||||
}{
|
||||
{"first", time.Time{}, "00000000-0000-0000-0000-000000000000"},
|
||||
{"late", lateTime, lateID},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var plan []byte
|
||||
err := f.db.QueryRow(ctx, `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid)
|
||||
ORDER BY created_at,id LIMIT $4`, chat.ID, tc.at, tc.id, 51).Scan(&plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(plan, []byte("messages_history_idx")) || bytes.Contains(plan, []byte(`"Node Type": "Seq Scan"`)) {
|
||||
t.Fatalf("history page did not use the index: %s", plan)
|
||||
}
|
||||
t.Logf("%s page EXPLAIN (ANALYZE, BUFFERS): %s", tc.name, plan)
|
||||
})
|
||||
}
|
||||
var count int
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM messages WHERE chat_id=$1", chat.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count < 10000 {
|
||||
t.Fatal(fmt.Errorf("history contains only %d messages", count))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
func TestIdempotencyConcurrentStoresAndScopes(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
alice, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
bob, _ := createTestUser(t, f.users, "bob", "Bob")
|
||||
chat := createTestChat(t, f.chats, "Chat", []string{alice.ID, bob.ID})
|
||||
otherChat := createTestChat(t, f.chats, "Other", []string{alice.ID})
|
||||
stores := []*repositories.MessageStore{f.messages, repositories.NewMessageStore(f.db)}
|
||||
const concurrency = 24
|
||||
start := make(chan struct{})
|
||||
results := make(chan repositories.Message, concurrency)
|
||||
errorsFound := make(chan error, concurrency)
|
||||
var group sync.WaitGroup
|
||||
for i := 0; i < concurrency; i++ {
|
||||
group.Add(1)
|
||||
go func(i int) {
|
||||
defer group.Done()
|
||||
<-start
|
||||
message, err := stores[i%len(stores)].CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "same-key")
|
||||
results <- message
|
||||
errorsFound <- err
|
||||
}(i)
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
close(results)
|
||||
close(errorsFound)
|
||||
for err := range errorsFound {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var original repositories.Message
|
||||
for message := range results {
|
||||
if original.ID == "" {
|
||||
original = message
|
||||
} else if message != original {
|
||||
t.Fatalf("replay changed the message: %v != %v", message, original)
|
||||
}
|
||||
}
|
||||
if len(listTestMessages(t, f.messages, chat.ID)) != 1 {
|
||||
t.Fatal("concurrent repeat created duplicate messages")
|
||||
}
|
||||
if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "different", "same-key"); !errors.Is(err, repositories.ErrIdempotencyConflict) {
|
||||
t.Fatalf("different body: got %v", err)
|
||||
}
|
||||
for _, scope := range [][2]string{{chat.ID, bob.ID}, {otherChat.ID, alice.ID}} {
|
||||
message, err := f.messages.CreateIdempotent(context.Background(), scope[0], scope[1], "hello", "same-key")
|
||||
if err != nil || message.ID == original.ID {
|
||||
t.Fatalf("key leaked across scopes: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := f.db.Exec(context.Background(), "UPDATE message_idempotency SET expires_at=now()-interval '1 second' WHERE message_id=$1", original.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reused, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "after expiry", "same-key")
|
||||
if err != nil || reused.ID == original.ID {
|
||||
t.Fatalf("expired key cannot be reused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyRecordFailureRollsBackMessage(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
alice, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
chat := createTestChat(t, f.chats, "Chat", []string{alice.ID})
|
||||
// Force a failure AFTER the message insert to verify transaction atomicity.
|
||||
_, err := f.db.Exec(context.Background(), `
|
||||
CREATE FUNCTION reject_replay() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'synthetic replay failure'; END $$;
|
||||
CREATE TRIGGER reject_replay BEFORE INSERT ON message_idempotency
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_replay()`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "retry-key"); err == nil {
|
||||
t.Fatal("synthetic failure did not happen")
|
||||
}
|
||||
if len(listTestMessages(t, f.messages, chat.ID)) != 0 {
|
||||
t.Fatal("failed transaction left a message behind")
|
||||
}
|
||||
if _, err := f.db.Exec(context.Background(), "DROP TRIGGER reject_replay ON message_idempotency"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.messages.CreateIdempotent(context.Background(), chat.ID, alice.ID, "hello", "retry-key"); err != nil {
|
||||
t.Fatalf("failure was cached instead of permitting retry: %v", err)
|
||||
}
|
||||
if len(listTestMessages(t, f.messages, chat.ID)) != 1 {
|
||||
t.Fatal("retry did not produce exactly one message")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestMessengerWorkflow(t *testing.T) {
|
||||
router := newTestFixture(t).router
|
||||
|
||||
call := func(method, path, body, auth string, expected int) map[string]any {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
|
||||
request.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
if auth != "" {
|
||||
request.Header.Set("Authorization", auth)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != expected {
|
||||
t.Fatalf("%s %s: status %d, want %d: %s", method, path, response.Code, expected, response.Body.String())
|
||||
}
|
||||
if response.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatalf("%s %s: missing request ID", method, path)
|
||||
}
|
||||
if response.Code == http.StatusNoContent {
|
||||
return nil
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
user := call("POST", "/api/v1/users", `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`, "", 201)
|
||||
userID := user["id"].(string)
|
||||
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password"))
|
||||
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
|
||||
bearer := "Bearer " + session["token"].(string)
|
||||
call("GET", "/api/v1/users/me", "", bearer, 200)
|
||||
chat := call("POST", "/api/v1/chats", `{"title":"Тестовый чат","member_ids":["`+userID+`"]}`, bearer, 201)
|
||||
chatID := chat["id"].(string)
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
for i := 0; i < 3; i++ {
|
||||
call("POST", path, `{"text":"message"}`, bearer, 201)
|
||||
}
|
||||
page1 := call("GET", path+"?limit=2", "", bearer, 200)
|
||||
first := page1["items"].([]any)
|
||||
if len(first) != 2 || page1["next_cursor"] == nil {
|
||||
t.Fatalf("unexpected first page: %v", page1)
|
||||
}
|
||||
page2 := call("GET", path+"?limit=2&cursor="+url.QueryEscape(page1["next_cursor"].(string)), "", bearer, 200)
|
||||
second := page2["items"].([]any)
|
||||
if len(second) != 1 || page2["next_cursor"] != nil || first[0].(map[string]any)["id"] == second[0].(map[string]any)["id"] {
|
||||
t.Fatalf("unexpected second page: %v", page2)
|
||||
}
|
||||
call("DELETE", "/api/v1/auth/sessions/current", "", bearer, 204)
|
||||
call("GET", "/api/v1/users/me", "", bearer, 401)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestDecodeJSONBodyRequiresExactFieldNames(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
user, _ := createTestUser(t, fixture.users, "json_tester", "JSON tester")
|
||||
chat := createTestChat(t, fixture.chats, "JSON body tests", []string{user.ID})
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
valid bool
|
||||
}{
|
||||
{"canonical", `{"text":"first","attachment_ids":[]}`, true},
|
||||
{"escaped canonical name", `{"te\u0078t":"first"}`, true},
|
||||
{"uppercase extra", `{"text":"first","TEXT":"second"}`, false},
|
||||
{"uppercase extra first", `{"TEXT":"second","text":"first"}`, false},
|
||||
{"mixed case", `{"Text":"second"}`, false},
|
||||
{"uppercase attachments", `{"text":"first","ATTACHMENT_IDS":[]}`, false},
|
||||
{"escaped uppercase", `{"text":"first","\u0054EXT":"second"}`, false},
|
||||
{"unknown field", `{"text":"first","sender_id":"other"}`, false},
|
||||
{"wrong type", `{"text":123}`, false},
|
||||
{"null", `null`, false},
|
||||
{"array", `[]`, false},
|
||||
{"trailing object", `{"text":"first"}{}`, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(test.body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
authorizeTestRequest(t, fixture, request, user.ID)
|
||||
response := httptest.NewRecorder()
|
||||
fixture.router.ServeHTTP(response, request)
|
||||
want := http.StatusBadRequest
|
||||
if test.valid {
|
||||
want = http.StatusCreated
|
||||
}
|
||||
if response.Code != want {
|
||||
t.Fatalf("want %d, got %d: %s", want, response.Code, response.Body.String())
|
||||
}
|
||||
if test.valid {
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value["text"] != "first" {
|
||||
t.Fatal("text changed")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCreateMessageBlankText(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||
|
||||
user, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||
if !created {
|
||||
t.Fatal("expected user to be created")
|
||||
}
|
||||
|
||||
chat := createTestChat(t, chatStore,
|
||||
"Тестовый чат",
|
||||
[]string{user.ID},
|
||||
)
|
||||
|
||||
handler := fixture.router
|
||||
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+chat.ID+"/messages",
|
||||
strings.NewReader(`{"text":" \t\n"}`),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
authorizeTestRequest(t, fixture, request, user.ID)
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected status %d, got %d; body: %s",
|
||||
http.StatusBadRequest,
|
||||
response.Code,
|
||||
response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
if response.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("expected non-empty X-Request-Id header")
|
||||
}
|
||||
|
||||
if !strings.Contains(
|
||||
response.Body.String(),
|
||||
`"code":"invalid_request"`,
|
||||
) {
|
||||
t.Fatalf(
|
||||
"expected invalid_request error code, got body: %s",
|
||||
response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
messages := listTestMessages(t, messageStore, chat.ID)
|
||||
|
||||
if len(messages) != 0 {
|
||||
t.Fatalf(
|
||||
"expected no messages to be stored, got %d",
|
||||
len(messages),
|
||||
)
|
||||
}
|
||||
}
|
||||
func TestCreateMessageFromChatOutsider(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||
|
||||
alice, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||
if !created {
|
||||
t.Fatal("expected Alice to be created")
|
||||
}
|
||||
|
||||
bob, created := createTestUser(t, userStore, "bob", "Боб")
|
||||
if !created {
|
||||
t.Fatal("expected Bob to be created")
|
||||
}
|
||||
|
||||
chat := createTestChat(t, chatStore,
|
||||
"Чат Алисы",
|
||||
[]string{alice.ID},
|
||||
)
|
||||
|
||||
handler := fixture.router
|
||||
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+chat.ID+"/messages",
|
||||
strings.NewReader(`{"text":"Сообщение чужому чату"}`),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
authorizeTestRequest(t, fixture, request, bob.ID)
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf(
|
||||
"expected status %d, got %d; body: %s",
|
||||
http.StatusNotFound,
|
||||
response.Code,
|
||||
response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
if response.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("expected non-empty X-Request-Id header")
|
||||
}
|
||||
|
||||
if !strings.Contains(
|
||||
response.Body.String(),
|
||||
`"code":"not_found"`,
|
||||
) {
|
||||
t.Fatalf(
|
||||
"expected not_found error code, got body: %s",
|
||||
response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
messages := listTestMessages(t, messageStore, chat.ID)
|
||||
|
||||
if len(messages) != 0 {
|
||||
t.Fatalf(
|
||||
"expected no messages to be stored, got %d",
|
||||
len(messages),
|
||||
)
|
||||
}
|
||||
}
|
||||
func TestListMessagesPagination(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||
|
||||
user, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||
if !created {
|
||||
t.Fatal("expected user to be created")
|
||||
}
|
||||
|
||||
chat := createTestChat(t, chatStore,
|
||||
"Тестовый чат",
|
||||
[]string{user.ID},
|
||||
)
|
||||
|
||||
first := createTestMessage(t, messageStore, chat.ID, user.ID, "Первое сообщение")
|
||||
second := createTestMessage(t, messageStore, chat.ID, user.ID, "Второе сообщение")
|
||||
third := createTestMessage(t, messageStore, chat.ID, user.ID, "Третье сообщение")
|
||||
|
||||
expectedIDs := map[string]bool{
|
||||
first.ID: true,
|
||||
second.ID: true,
|
||||
third.ID: true,
|
||||
}
|
||||
|
||||
handler := fixture.router
|
||||
|
||||
// Запрашиваем только два сообщения из трёх.
|
||||
firstRequest := httptest.NewRequest(
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+chat.ID+"/messages?limit=2",
|
||||
nil,
|
||||
)
|
||||
authorizeTestRequest(t, fixture, firstRequest, user.ID)
|
||||
|
||||
firstResponse := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(firstResponse, firstRequest)
|
||||
|
||||
if firstResponse.Code != http.StatusOK {
|
||||
t.Fatalf(
|
||||
"expected first page status %d, got %d; body: %s",
|
||||
http.StatusOK,
|
||||
firstResponse.Code,
|
||||
firstResponse.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
var firstPage messagePage
|
||||
|
||||
if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil {
|
||||
t.Fatalf("failed to decode first page: %v", err)
|
||||
}
|
||||
|
||||
if len(firstPage.Items) != 2 {
|
||||
t.Fatalf(
|
||||
"expected 2 messages on first page, got %d",
|
||||
len(firstPage.Items),
|
||||
)
|
||||
}
|
||||
|
||||
if firstPage.NextCursor == nil || *firstPage.NextCursor == "" {
|
||||
t.Fatal("expected non-empty next cursor on first page")
|
||||
}
|
||||
|
||||
// Проверяем, что сообщения на первой странице уникальны
|
||||
// и принадлежат исходному набору.
|
||||
seenIDs := make(map[string]bool)
|
||||
|
||||
for _, message := range firstPage.Items {
|
||||
if !expectedIDs[message.ID] {
|
||||
t.Fatalf("unexpected message ID on first page: %s", message.ID)
|
||||
}
|
||||
|
||||
if seenIDs[message.ID] {
|
||||
t.Fatalf("duplicate message on first page: %s", message.ID)
|
||||
}
|
||||
|
||||
seenIDs[message.ID] = true
|
||||
}
|
||||
|
||||
// Используем cursor первой страницы для получения второй.
|
||||
secondRequest := httptest.NewRequest(
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+
|
||||
url.QueryEscape(*firstPage.NextCursor),
|
||||
nil,
|
||||
)
|
||||
authorizeTestRequest(t, fixture, secondRequest, user.ID)
|
||||
|
||||
secondResponse := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(secondResponse, secondRequest)
|
||||
|
||||
if secondResponse.Code != http.StatusOK {
|
||||
t.Fatalf(
|
||||
"expected second page status %d, got %d; body: %s",
|
||||
http.StatusOK,
|
||||
secondResponse.Code,
|
||||
secondResponse.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
var secondPage messagePage
|
||||
|
||||
if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil {
|
||||
t.Fatalf("failed to decode second page: %v", err)
|
||||
}
|
||||
|
||||
if len(secondPage.Items) != 1 {
|
||||
t.Fatalf(
|
||||
"expected 1 message on second page, got %d",
|
||||
len(secondPage.Items),
|
||||
)
|
||||
}
|
||||
|
||||
if secondPage.NextCursor != nil {
|
||||
t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor)
|
||||
}
|
||||
|
||||
// Проверяем, что вторая страница не повторяет первую.
|
||||
for _, message := range secondPage.Items {
|
||||
if seenIDs[message.ID] {
|
||||
t.Fatalf("message repeated on second page: %s", message.ID)
|
||||
}
|
||||
|
||||
if !expectedIDs[message.ID] {
|
||||
t.Fatalf("unexpected message ID on second page: %s", message.ID)
|
||||
}
|
||||
|
||||
seenIDs[message.ID] = true
|
||||
}
|
||||
|
||||
if len(seenIDs) != len(expectedIDs) {
|
||||
t.Fatalf(
|
||||
"pagination lost messages: expected %d unique messages, got %d",
|
||||
len(expectedIDs),
|
||||
len(seenIDs),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestListPageByChatUsesCursorAndLimit(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||
chat := createTestChat(t, f.chats, "Пагинация", []string{user.ID})
|
||||
other := createTestChat(t, f.chats, "Другой чат", []string{user.ID})
|
||||
createTestMessage(t, f.messages, other.ID, user.ID, "Не должно попасть в страницу")
|
||||
createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC)
|
||||
ids := []string{
|
||||
"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002",
|
||||
"00000000-0000-4000-8000-000000000003", "00000000-0000-4000-8000-000000000004",
|
||||
}
|
||||
// Insert in reverse order to exercise SQL ordering, including equal timestamps.
|
||||
for i := len(ids) - 1; i >= 0; i-- {
|
||||
at := createdAt
|
||||
if i > 1 {
|
||||
at = at.Add(time.Duration(i-1) * time.Second)
|
||||
}
|
||||
_, err := f.db.Exec(context.Background(), "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", ids[i], chat.ID, user.ID, "message", at)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
first, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, nil, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !more || len(first) != 2 || first[0].ID != ids[0] || first[1].ID != ids[1] {
|
||||
t.Fatalf("unexpected first page: %v, more=%v", first, more)
|
||||
}
|
||||
cursor := &messageCursor{ChatID: chat.ID, CreatedAt: first[1].CreatedAt, MessageID: first[1].ID}
|
||||
second, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, cursor, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if more || len(second) != 2 || second[0].ID != ids[2] || second[1].ID != ids[3] {
|
||||
t.Fatalf("unexpected second page: %v, more=%v", second, more)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
page, more, err := f.messages.ListPageByChat(context.Background(), uuid.NewString(), nil, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page == nil || len(page) != 0 || more {
|
||||
t.Fatalf("unexpected empty page: %v, more=%v", page, more)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/services"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) {
|
||||
password := "длинный-пароль-с-эмодзи-🔒-0123456789"
|
||||
first, err := services.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := services.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.HasPrefix(first, []byte("$argon2id$v=19$m=65536,t=3,p=2$")) || bytes.Equal(first, second) {
|
||||
t.Fatal("password hashes must use Argon2id with independent salts")
|
||||
}
|
||||
valid, err := services.VerifyPassword(password, first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
invalid, err := services.VerifyPassword(password+"другое", first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !valid || invalid {
|
||||
t.Fatal("Argon2id verification lost the full UTF-8 password")
|
||||
}
|
||||
if _, err := services.VerifyPassword(password, bytes.Repeat([]byte{1}, 64)); err == nil {
|
||||
t.Fatal("legacy scrypt hash must not be accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoredPasswordUsesArgon2id(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
user, _ := createTestUser(t, fixture.users, "alice", "Алиса")
|
||||
var stored []byte
|
||||
if err := fixture.db.QueryRow(context.Background(), "SELECT password_hash FROM users WHERE id=$1", user.ID).Scan(&stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.HasPrefix(stored, []byte("$argon2id$")) {
|
||||
t.Fatalf("unexpected stored password hash format: %q", stored)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerRequiredIgnoresXUserID(t *testing.T) {
|
||||
handler := handlers.NewRouter(nil, nil, nil, nil, nil)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatalf("unexpected response: %d %v", response.Code, response.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageCursorPreservesPosition(t *testing.T) {
|
||||
original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"}
|
||||
token, err := services.EncodeMessageCursor(original)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := services.DecodeMessageCursor(token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decoded != original {
|
||||
t.Fatalf("cursor changed: %+v", decoded)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type testFixture struct {
|
||||
db *pgxpool.Pool
|
||||
users *repositories.UserStore
|
||||
chats *repositories.ChatStore
|
||||
messages *repositories.MessageStore
|
||||
sessionStore *repositories.SessionStore
|
||||
sessions *services.SessionService
|
||||
router http.Handler
|
||||
}
|
||||
|
||||
// Each test owns a new schema; public application tables are never modified.
|
||||
func newTestFixture(t *testing.T) *testFixture {
|
||||
t.Helper()
|
||||
url := os.Getenv("TEST_DATABASE_URL")
|
||||
redisAddress := os.Getenv("TEST_REDIS_ADDR")
|
||||
if url == "" || redisAddress == "" {
|
||||
t.Skip("integration tests: run make test-backend, or set TEST_DATABASE_URL and TEST_REDIS_ADDR")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
admin, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(admin.Close)
|
||||
schema := "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
identifier := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+identifier); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
|
||||
t.Errorf("cleanup test schema: %v", err)
|
||||
}
|
||||
})
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(db.Close)
|
||||
ddl, err := os.ReadFile("../repositories/migrations/000001_initial.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000002_redis_sessions.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
redisClient := repositories.NewRedisClient(redisAddress)
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000003_message_idempotency.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users := repositories.NewUserStore(db)
|
||||
chats := repositories.NewChatStore(db)
|
||||
messages := repositories.NewMessageStore(db)
|
||||
userService := services.NewUserService(users)
|
||||
sessionStore := repositories.NewSessionStore(redisClient, "test:"+schema+":session:")
|
||||
sessions := services.NewSessionService(userService, sessionStore, time.Hour)
|
||||
router := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessions, services.NewChatService(chats), services.NewMessageService(messages))
|
||||
return &testFixture{db: db, users: users, chats: chats, messages: messages, sessionStore: sessionStore, sessions: sessions, router: router}
|
||||
}
|
||||
|
||||
func createTestUser(t *testing.T, store *repositories.UserStore, username, name string) (repositories.User, bool) {
|
||||
t.Helper()
|
||||
user, err := services.NewUserService(store).Create(context.Background(), username, name, "lab2-test-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func createTestChat(t *testing.T, store *repositories.ChatStore, title string, members []string) repositories.Chat {
|
||||
t.Helper()
|
||||
chat, err := store.Create(context.Background(), title, members)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return chat
|
||||
}
|
||||
|
||||
func createTestMessage(t *testing.T, store *repositories.MessageStore, chatID, userID, text string) repositories.Message {
|
||||
t.Helper()
|
||||
message, err := store.Create(context.Background(), chatID, userID, text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func listTestMessages(t *testing.T, store *repositories.MessageStore, chatID string) []repositories.Message {
|
||||
t.Helper()
|
||||
items, _, err := store.ListPageByChat(context.Background(), chatID, nil, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func authorizeTestRequest(t *testing.T, fixture *testFixture, request *http.Request, userID string) {
|
||||
t.Helper()
|
||||
token, _, err := fixture.sessions.CreateForUser(request.Context(), userID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
type User = repositories.User
|
||||
type Chat = repositories.Chat
|
||||
type messagePage = services.MessagePage
|
||||
type messageCursor = repositories.MessageCursor
|
||||
@@ -0,0 +1,137 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCreateUserInvalidJSON(t *testing.T) {
|
||||
store := repositories.NewUserStore(nil)
|
||||
handler := handlers.NewRouter(nil, services.NewUserService(store), nil, nil, nil)
|
||||
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/users",
|
||||
strings.NewReader(`{"username":`),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected status %d, got %d; body: %s",
|
||||
http.StatusBadRequest,
|
||||
response.Code,
|
||||
response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
if response.Header().Get("Content-Type") != "application/json" {
|
||||
t.Fatalf(
|
||||
"expected Content-Type application/json, got %q",
|
||||
response.Header().Get("Content-Type"),
|
||||
)
|
||||
}
|
||||
|
||||
if response.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("expected non-empty X-Request-Id header")
|
||||
}
|
||||
|
||||
body := response.Body.String()
|
||||
|
||||
if !strings.Contains(body, `"code":"invalid_request"`) {
|
||||
t.Fatalf(
|
||||
"expected invalid_request error code, got body: %s",
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "request_id") {
|
||||
t.Fatalf(
|
||||
"expected request_id in error body, got body: %s",
|
||||
body,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUserDuplicateUsername(t *testing.T) {
|
||||
fixture := newTestFixture(t)
|
||||
handler := fixture.router
|
||||
|
||||
firstRequest := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/users",
|
||||
strings.NewReader(`{
|
||||
"username": "alice",
|
||||
"display_name": "Алиса", "password": "lab2-test-password"
|
||||
}`),
|
||||
)
|
||||
firstRequest.Header.Set("Content-Type", "application/json")
|
||||
|
||||
firstResponse := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(firstResponse, firstRequest)
|
||||
|
||||
if firstResponse.Code != http.StatusCreated {
|
||||
t.Fatalf(
|
||||
"expected first request status %d, got %d; body: %s",
|
||||
http.StatusCreated,
|
||||
firstResponse.Code,
|
||||
firstResponse.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
secondRequest := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/users",
|
||||
strings.NewReader(`{
|
||||
"username": "alice",
|
||||
"display_name": "Другая Алиса", "password": "lab2-test-password"
|
||||
}`),
|
||||
)
|
||||
secondRequest.Header.Set("Content-Type", "application/json")
|
||||
|
||||
secondResponse := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(secondResponse, secondRequest)
|
||||
|
||||
if secondResponse.Code != http.StatusConflict {
|
||||
t.Fatalf(
|
||||
"expected duplicate username status %d, got %d; body: %s",
|
||||
http.StatusConflict,
|
||||
secondResponse.Code,
|
||||
secondResponse.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
if secondResponse.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("expected non-empty X-Request-Id header")
|
||||
}
|
||||
|
||||
if !strings.Contains(
|
||||
secondResponse.Body.String(),
|
||||
`"code":"conflict"`,
|
||||
) {
|
||||
t.Fatalf(
|
||||
"expected conflict error code, got body: %s",
|
||||
secondResponse.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := fixture.db.QueryRow(context.Background(), "SELECT count(*) FROM users").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("expected one user, got %d", count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/services"
|
||||
)
|
||||
|
||||
func TestCaseVariantExtraFieldsReturn400WithoutSaving(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
chat := createTestChat(t, f.chats, "Chat", []string{user.ID})
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
key := uuid.NewString()
|
||||
send := func(path, body, key string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("Idempotency-Key", key)
|
||||
authorizeTestRequest(t, f, r, user.ID)
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, test := range []struct{ path, body string }{
|
||||
{path, `{"text":"first","TEXT":"second"}`},
|
||||
{path, `{"TEXT":"second","text":"first"}`},
|
||||
{path, `{"Text":"second"}`},
|
||||
{path, `{"text":"first","Attachment_IDs":[]}`},
|
||||
{"/api/v1/chats", fmt.Sprintf(`{"title":"Chat","TITLE":"other","member_ids":[%q]}`, user.ID)},
|
||||
{"/api/v1/chats", fmt.Sprintf(`{"title":"Chat","MEMBER_IDS":[%q]}`, user.ID)},
|
||||
{"/api/v1/users", `{"username":"new","USERNAME":"other","display_name":"New","password":"test-password"}`},
|
||||
{"/api/v1/users", `{"username":"new","display_name":"New","Password":"test-password"}`},
|
||||
} {
|
||||
w := send(test.path, test.body, key)
|
||||
if w.Code != 400 || !strings.Contains(w.Body.String(), `"code":"invalid_request"`) {
|
||||
t.Fatalf("%s: want invalid_request 400, got %d %s", test.path, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
if len(listTestMessages(t, f.messages, chat.ID)) != 0 {
|
||||
t.Fatal("rejected request saved a message")
|
||||
}
|
||||
w := send(path, `{"text":"first"}`, key)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("corrected request with same key: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w = send(path, `{"text":"first","attachment_ids":[]}`, key); w.Code != 201 {
|
||||
t.Fatalf("valid replay: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
messages := listTestMessages(t, f.messages, chat.ID)
|
||||
if len(messages) != 1 || messages[0].Text != "first" {
|
||||
t.Fatal("wrong message or duplicate saved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRejectsCaseVariantDuplicateMembersBeforeSQL(t *testing.T) {
|
||||
const id = "abcdef01-abcd-4abc-8abc-abcdef012345"
|
||||
for _, members := range [][]string{{id, strings.ToUpper(id)}, {strings.ToUpper(id), id}} {
|
||||
_, err := services.NewChatService(nil).Create(context.Background(), id, "Chat", members)
|
||||
var invalid services.InvalidInput
|
||||
if !errors.As(err, &invalid) {
|
||||
t.Fatalf("want InvalidInput before SQL, got %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatNormalizesMemberUUIDsHTTP(t *testing.T) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
for _, duplicate := range []bool{true, false} {
|
||||
members := fmt.Sprintf(`[%q]`, strings.ToUpper(user.ID))
|
||||
want := 201
|
||||
if duplicate {
|
||||
members = fmt.Sprintf(`[%q,%q]`, user.ID, strings.ToUpper(user.ID))
|
||||
want = 400
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/chats", strings.NewReader(`{"title":"Chat","member_ids":`+members+`}`))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
authorizeTestRequest(t, f, r, user.ID)
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("duplicate=%v: want %d, got %d %s", duplicate, want, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
var chats, members int
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&chats); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chat_members").Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 1 || members != 1 {
|
||||
t.Fatalf("unexpected persisted chats=%d members=%d", chats, members)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user