fix: update env and PR template
This commit is contained in:
+16
-6
@@ -32,10 +32,17 @@ func serverAddress() string {
|
||||
}
|
||||
|
||||
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}
|
||||
response, err := client.Get("http://127.0.0.1:8080/health/ready")
|
||||
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)
|
||||
}
|
||||
@@ -81,16 +88,19 @@ func main() {
|
||||
}
|
||||
}()
|
||||
}
|
||||
redisAddress := os.Getenv("REDIS_ADDR")
|
||||
if redisAddress == "" {
|
||||
redisAddress = "redis:6379"
|
||||
redisClient, err := repositories.RedisClientFromEnvironment()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
redisClient := repositories.NewRedisClient(redisAddress)
|
||||
defer redisClient.Close()
|
||||
sessionStore := repositories.NewSessionStore(redisClient, "messenger:session:")
|
||||
userStore := repositories.NewUserStore(db)
|
||||
chatStore := repositories.NewChatStore(db)
|
||||
messageStore := repositories.NewMessageStore(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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
|
||||
return Message{}, err
|
||||
}
|
||||
|
||||
// Expiry permits reuse after 24 hours; it never deletes the original message.
|
||||
// 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
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
|
||||
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 {
|
||||
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)
|
||||
|
||||
@@ -17,11 +17,16 @@ type Message struct {
|
||||
}
|
||||
|
||||
type MessageStore struct {
|
||||
db *pgxpool.Pool
|
||||
db *pgxpool.Pool
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageStore(db *pgxpool.Pool) *MessageStore {
|
||||
return &MessageStore{db: db}
|
||||
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(
|
||||
|
||||
@@ -99,6 +99,12 @@ func DecodeChatCursor(value string) (repositories.ChatCursor, error) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
@@ -42,6 +43,12 @@ func DecodeMessageCursor(value string) (repositories.MessageCursor, error) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ func SessionTTL() (time.Duration, error) {
|
||||
return time.Hour, nil
|
||||
}
|
||||
seconds, err := strconv.Atoi(value)
|
||||
if err != nil || seconds < 1 {
|
||||
if err != nil || seconds < 1 || seconds > 31536000 {
|
||||
return 0, errors.New("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user