forked from mtusi2026/mtusi2026lab3
feat: add HAproxy and 2 api instances
This commit is contained in:
@@ -49,7 +49,7 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) {
|
||||
case errors.As(err, &invalid):
|
||||
writeError(w, 400, "invalid_request", invalid.Message, requestID)
|
||||
case errors.Is(err, services.ErrConflict):
|
||||
writeError(w, 409, "conflict", "username is already taken", requestID)
|
||||
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):
|
||||
@@ -139,5 +139,5 @@ func NewRouter(health *services.HealthService, users *services.UserService, sess
|
||||
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 mux
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -9,7 +10,8 @@ import (
|
||||
)
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs json.RawMessage `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func messageChatID(path string) (string, bool) {
|
||||
@@ -60,7 +62,19 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag
|
||||
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||
return
|
||||
}
|
||||
message, err := messages.Create(r.Context(), userID, chat, request.Text)
|
||||
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
|
||||
|
||||
@@ -116,6 +116,7 @@ func main() {
|
||||
|
||||
case <-shutdownContext.Done():
|
||||
log.Printf("shutdown signal received")
|
||||
handlers.BeginShutdown()
|
||||
|
||||
shutdownDeadline, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
|
||||
@@ -52,10 +52,6 @@ func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = RunMigrations(url, "up"); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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 reuse after 24 hours; 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() + interval '24 hours')`, senderID, chatID, key, message.ID); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
return message, tx.Commit(ctx)
|
||||
}
|
||||
@@ -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,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
|
||||
}
|
||||
@@ -87,6 +87,7 @@ func TestConcurrentMessageCreation(t *testing.T) {
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestMessengerWorkflow(t *testing.T) {
|
||||
@@ -19,6 +22,9 @@ func TestMessengerWorkflow(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -78,6 +78,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user