7 Commits
60 changed files with 3517 additions and 4 deletions
+4 -4
View File
@@ -1,10 +1,10 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080 APP_PORT=8080
APP_ENV=lab MAX_INFLIGHT_REQUESTS=0
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
LOG_LEVEL=INFO
DATABASE_URL_FILE=/run/secrets/database_url DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey: # Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres SESSION_STORE=postgres
+21
View File
@@ -0,0 +1,21 @@
FROM golang:1.25.0 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /out/server ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /app
COPY --from=build /out/server .
COPY contracts ./contracts
COPY web/swagger ./web/swagger
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD ["/app/server", "healthcheck"]
ENTRYPOINT ["/app/server"]
+8
View File
@@ -0,0 +1,8 @@
FROM golang:1.27.1-alpine3.24 AS build
ENV CGO_ENABLED=0
RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0
FROM alpine:3.24
COPY --from=build /go/bin/goose /usr/local/bin/goose
COPY db/migrations /migrations
ENTRYPOINT ["sh", "-c", "goose -dir /migrations postgres \"$(cat /run/secrets/database_url)\" up"]
+2
View File
@@ -24,3 +24,5 @@ load:
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
-include student.mk
+18
View File
@@ -0,0 +1,18 @@
package main
import (
"log"
"os"
"mtusi2026-messenger/internal/app"
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(app.Healthcheck())
}
if err := app.Run(); err != nil {
log.Fatal(err)
}
}
+51
View File
@@ -0,0 +1,51 @@
-- +goose Up
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL
CONSTRAINT users_display_name_not_blank CHECK (display_name ~ '\S'),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE sessions (
token_hash text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL
);
CREATE INDEX idx_sessions_expires_at ON sessions (expires_at);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL
CONSTRAINT chats_title_not_blank CHECK (title ~ '\S'),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX idx_chat_members_user_id ON chat_members (user_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id);
-- +goose Down
DROP TABLE messages;
DROP TABLE chat_members;
DROP TABLE chats;
DROP TABLE sessions;
DROP TABLE users;
+62
View File
@@ -0,0 +1,62 @@
-- name: CreateChat :one
INSERT INTO chats (
id,
title
) VALUES (
sqlc.arg(id),
sqlc.arg(title)
)
RETURNING *;
-- name: AddChatMembers :exec
INSERT INTO chat_members (
chat_id,
user_id
)
SELECT
sqlc.arg(chat_id)::uuid,
unnest(sqlc.arg(user_ids)::uuid[]);
-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(user_id)
);
-- name: GetChat :one
SELECT
c.*,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
WHERE c.id = sqlc.arg(id)
AND EXISTS (
SELECT 1 FROM chat_members m
WHERE m.chat_id = c.id
AND m.user_id = sqlc.arg(user_id)
);
-- name: ListChats :many
SELECT
c.*,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = sqlc.arg(user_id)
AND (
sqlc.narg(after_created_at)::timestamptz IS NULL
OR (c.created_at, c.id) > (
sqlc.narg(after_created_at)::timestamptz,
sqlc.narg(after_id)::uuid
)
)
ORDER BY c.created_at, c.id
LIMIT sqlc.arg(lim);
+31
View File
@@ -0,0 +1,31 @@
-- name: CreateMessage :one
INSERT INTO messages (
id,
chat_id,
sender_id,
text
)
SELECT
sqlc.arg(id)::uuid,
sqlc.arg(chat_id)::uuid,
sqlc.arg(sender_id)::uuid,
sqlc.arg(text)::text
WHERE EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(sender_id)
)
RETURNING *;
-- name: ListMessages :many
SELECT * FROM messages
WHERE chat_id = sqlc.arg(chat_id)
AND (
sqlc.narg(after_created_at)::timestamptz IS NULL
OR (created_at, id) > (
sqlc.narg(after_created_at)::timestamptz,
sqlc.narg(after_id)::uuid
)
)
ORDER BY created_at, id
LIMIT sqlc.arg(lim);
+24
View File
@@ -0,0 +1,24 @@
-- name: CreateSession :exec
INSERT INTO sessions (
token_hash,
user_id,
expires_at
) VALUES (
sqlc.arg(token_hash),
sqlc.arg(user_id),
sqlc.arg(expires_at)
);
-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = sqlc.arg(token_hash)
AND s.expires_at > now();
-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = sqlc.arg(token_hash);
-- name: DeleteExpiredSessions :execrows
DELETE FROM sessions
WHERE expires_at <= now();
+21
View File
@@ -0,0 +1,21 @@
-- name: CreateUser :one
INSERT INTO users (
id,
username,
display_name,
password_hash
) VALUES (
sqlc.arg(id),
sqlc.arg(username),
sqlc.arg(display_name),
sqlc.arg(password_hash)
)
RETURNING id, username, display_name, created_at;
-- name: GetUser :one
SELECT id, username, display_name, created_at FROM users
WHERE id = sqlc.arg(id);
-- name: GetUserByUsername :one
SELECT * FROM users
WHERE username = sqlc.arg(username);
+53
View File
@@ -0,0 +1,53 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab2
ports:
- "127.0.0.1:8080:${APP_PORT}"
env_file:
- .env
secrets:
- database_url
depends_on:
migrate:
condition: service_completed_successfully
restart: unless-stopped
postgres:
image: postgres:18.6
environment:
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 3s
retries: 10
restart: unless-stopped
migrate:
build:
context: .
dockerfile: Dockerfile.migrate
secrets:
- database_url
depends_on:
postgres:
condition: service_healthy
restart: "no"
secrets:
postgres_password:
file: ./secrets/postgres_password.txt
database_url:
file: ./secrets/database_url.txt
volumes:
pgdata:
+19
View File
@@ -0,0 +1,19 @@
module mtusi2026-messenger
go 1.26.0
require (
github.com/go-chi/chi/v5 v5.3.2
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/joho/godotenv v1.5.1
golang.org/x/crypto v0.57.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/text v0.42.0 // indirect
)
+34
View File
@@ -0,0 +1,34 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+96
View File
@@ -0,0 +1,96 @@
package app
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/joho/godotenv"
"mtusi2026-messenger/internal/config"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/logger"
"mtusi2026-messenger/internal/service"
"mtusi2026-messenger/internal/store"
)
func Run() error {
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
return err
}
cfg := config.Load()
log := logger.New(cfg.Logging.Level)
dbURL, err := cfg.Database.URL()
if err != nil {
log.Error("read database url", "error", err)
return err
}
pool, err := db.New(context.Background(), dbURL)
if err != nil {
log.Error("connect to database", "error", err)
return err
}
defer pool.Close()
memory := store.New()
userService := service.NewUserService(memory)
chatService := service.NewChatService(memory)
messageService := service.NewMessageService(memory)
router := NewRouter(
log,
cfg.Server.MaxInflightRequests,
pool,
userService,
chatService,
messageService,
)
server := &http.Server{
Addr: cfg.Server.Host + ":" + cfg.Server.Port,
Handler: router,
}
serverErrors := make(chan error, 1)
go func() {
log.Info("server starting", "addr", server.Addr)
serverErrors <- server.ListenAndServe()
}()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(signalCh)
select {
case err := <-serverErrors:
if err == http.ErrServerClosed {
return nil
}
log.Error("server failed", "error", err)
return err
case sig := <-signalCh:
log.Info("shutdown signal received", "signal", sig.String())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Error("server shutdown failed", "error", err)
return err
}
log.Info("server stopped")
return nil
}
}
+46
View File
@@ -0,0 +1,46 @@
package app
import (
"context"
"fmt"
"net/http"
"os"
"time"
"mtusi2026-messenger/internal/config"
"github.com/joho/godotenv"
)
func Healthcheck() int {
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, "healthcheck: load env:", err)
return 1
}
cfg := config.Load()
url := fmt.Sprintf("http://localhost:%s/health/ready", cfg.Server.Port)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck: build request:", err)
return 1
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck: request failed:", err)
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintln(os.Stderr, "healthcheck: unexpected status", resp.StatusCode)
return 1
}
return 0
}
+55
View File
@@ -0,0 +1,55 @@
package app
import (
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"mtusi2026-messenger/internal/handler"
"mtusi2026-messenger/internal/middleware"
"mtusi2026-messenger/internal/service"
)
func NewRouter(
log *slog.Logger,
maxInflightRequests int,
db handler.Pinger,
userService *service.UserService,
chatService *service.ChatService,
messageService *service.MessageService,
) http.Handler {
router := chi.NewRouter()
healthHandler := handler.NewHealthHandler(log, db)
userHandler := handler.NewUserHandler(userService)
chatHandler := handler.NewChatHandler(chatService)
messageHandler := handler.NewMessageHandler(messageService)
router.Use(middleware.RequestID)
router.Use(middleware.Logging(log))
router.Use(middleware.ConcurrencyLimit(maxInflightRequests))
router.Get("/health/live", healthHandler.Live)
router.Get("/health/ready", healthHandler.Ready)
router.Post("/api/v1/users", userHandler.Create)
router.Group(func(r chi.Router) {
r.Use(middleware.Auth(userService))
r.Get("/api/v1/users/me", userHandler.Me)
r.Post("/api/v1/chats", chatHandler.Create)
r.Get("/api/v1/chats", chatHandler.List)
r.Get("/api/v1/chats/{chat_id}", chatHandler.Get)
r.Post("/api/v1/chats/{chat_id}/messages", messageHandler.Create)
r.Get("/api/v1/chats/{chat_id}/messages", messageHandler.List)
})
router.Handle("/swagger/*", http.StripPrefix("/swagger/", http.FileServer(http.Dir("web/swagger"))))
router.Handle("/contracts/*", http.StripPrefix("/contracts/", http.FileServer(http.Dir("contracts"))))
return router
}
+128
View File
@@ -0,0 +1,128 @@
package config
import (
"fmt"
"log"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Server ServerConfig
Logging LoggingConfig
Database DatabaseConfig
}
type ServerConfig struct {
Host string
Port string
MaxInflightRequests int
SessionTTL time.Duration
}
type LoggingConfig struct {
Level slog.Level
}
type DatabaseConfig struct {
URLFile string
}
func (c DatabaseConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
func Load() Config {
return Config{
Server: ServerConfig{
Host: getEnv("APP_HOST", "0.0.0.0"),
Port: getEnv("APP_PORT", "8080"),
MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0),
SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second,
},
Logging: LoggingConfig{
Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo),
},
Database: DatabaseConfig{
URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"),
},
}
}
func getEnv(key, def string) string {
value := os.Getenv(key)
if value == "" {
return def
}
return value
}
func getEnvNonNegativeInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
value, err := strconv.Atoi(v)
if err != nil || value < 0 {
log.Printf("invalid non-negative int for %s=%q, using default %d", key, v, def)
return def
}
return value
}
func getEnvPositiveInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
value, err := strconv.Atoi(v)
if err != nil || value <= 0 {
log.Printf("invalid positive int for %s=%q, using default %d", key, v, def)
return def
}
return value
}
func getEnvLogLevel(key string, def slog.Level) slog.Level {
v := os.Getenv(key)
switch v {
case "DEBUG":
return slog.LevelDebug
case "INFO":
return slog.LevelInfo
case "WARN":
return slog.LevelWarn
case "ERROR":
return slog.LevelError
case "":
return def
default:
log.Printf("invalid log level for %s=%q, using default %s", key, v, def)
return def
}
}
func readSecretFile(path string) (string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read secret file %s: %w", path, err)
}
value := strings.TrimSpace(string(b))
if value == "" {
return "", fmt.Errorf("secret file %s is empty", path)
}
return value, nil
}
+51
View File
@@ -0,0 +1,51 @@
package credentials
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"golang.org/x/crypto/bcrypt"
)
const tokenSize = 32
var ErrPasswordMismatch = errors.New("password mismatch")
func prehash(plain string) []byte {
sum := sha256.Sum256([]byte(plain))
return []byte(base64.StdEncoding.EncodeToString(sum[:]))
}
func HashPassword(plain string) (string, error) {
hash, err := bcrypt.GenerateFromPassword(prehash(plain), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
func VerifyPassword(hash, plain string) error {
err := bcrypt.CompareHashAndPassword([]byte(hash), prehash(plain))
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return ErrPasswordMismatch
}
return err
}
func NewToken() string {
raw := make([]byte, tokenSize)
_, _ = rand.Read(raw) // never returns an error since Go 1.24
return base64.RawURLEncoding.EncodeToString(raw)
}
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
+183
View File
@@ -0,0 +1,183 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: chats.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const addChatMembers = `-- name: AddChatMembers :exec
INSERT INTO chat_members (
chat_id,
user_id
)
SELECT
$1::uuid,
unnest($2::uuid[])
`
type AddChatMembersParams struct {
ChatID uuid.UUID
UserIds []uuid.UUID
}
func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error {
_, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds)
return err
}
const createChat = `-- name: CreateChat :one
INSERT INTO chats (
id,
title
) VALUES (
$1,
$2
)
RETURNING id, title, created_at
`
type CreateChatParams struct {
ID uuid.UUID
Title string
}
func (q *Queries) CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) {
row := q.db.QueryRow(ctx, createChat, arg.ID, arg.Title)
var i Chat
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
return i, err
}
const getChat = `-- name: GetChat :one
SELECT
c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
WHERE c.id = $1
AND EXISTS (
SELECT 1 FROM chat_members m
WHERE m.chat_id = c.id
AND m.user_id = $2
)
`
type GetChatParams struct {
ID uuid.UUID
UserID uuid.UUID
}
type GetChatRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) {
row := q.db.QueryRow(ctx, getChat, arg.ID, arg.UserID)
var i GetChatRow
err := row.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
)
return i, err
}
const isChatMember = `-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`
type IsChatMemberParams struct {
ChatID uuid.UUID
UserID uuid.UUID
}
func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) {
row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const listChats = `-- name: ListChats :many
SELECT
c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1
AND (
$2::timestamptz IS NULL
OR (c.created_at, c.id) > (
$2::timestamptz,
$3::uuid
)
)
ORDER BY c.created_at, c.id
LIMIT $4
`
type ListChatsParams struct {
UserID uuid.UUID
AfterCreatedAt *time.Time
AfterID *uuid.UUID
Lim int32
}
type ListChatsRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
rows, err := q.db.Query(ctx, listChats,
arg.UserID,
arg.AfterCreatedAt,
arg.AfterID,
arg.Lim,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsRow{}
for rows.Next() {
var i ListChatsRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+32
View File
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package db
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
+110
View File
@@ -0,0 +1,110 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: messages.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const createMessage = `-- name: CreateMessage :one
INSERT INTO messages (
id,
chat_id,
sender_id,
text
)
SELECT
$1::uuid,
$2::uuid,
$3::uuid,
$4::text
WHERE EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = $2
AND user_id = $3
)
RETURNING id, chat_id, sender_id, text, created_at
`
type CreateMessageParams struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
}
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
row := q.db.QueryRow(ctx, createMessage,
arg.ID,
arg.ChatID,
arg.SenderID,
arg.Text,
)
var i Message
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
const listMessages = `-- name: ListMessages :many
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
AND (
$2::timestamptz IS NULL
OR (created_at, id) > (
$2::timestamptz,
$3::uuid
)
)
ORDER BY created_at, id
LIMIT $4
`
type ListMessagesParams struct {
ChatID uuid.UUID
AfterCreatedAt *time.Time
AfterID *uuid.UUID
Lim int32
}
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessages,
arg.ChatID,
arg.AfterCreatedAt,
arg.AfterID,
arg.Lim,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+45
View File
@@ -0,0 +1,45 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package db
import (
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type Session struct {
TokenHash string
UserID uuid.UUID
CreatedAt time.Time
ExpiresAt time.Time
}
type User struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
}
+30
View File
@@ -0,0 +1,30 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package db
import (
"context"
"github.com/google/uuid"
)
type Querier interface {
AddChatMembers(ctx context.Context, arg AddChatMembersParams) error
CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error)
CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)
CreateSession(ctx context.Context, arg CreateSessionParams) error
CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error)
DeleteExpiredSessions(ctx context.Context) (int64, error)
DeleteSession(ctx context.Context, tokenHash string) error
GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error)
GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error)
GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error)
GetUserByUsername(ctx context.Context, username string) (User, error)
IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error)
ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error)
ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error)
}
var _ Querier = (*Queries)(nil)
+85
View File
@@ -0,0 +1,85 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: sessions.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const createSession = `-- name: CreateSession :exec
INSERT INTO sessions (
token_hash,
user_id,
expires_at
) VALUES (
$1,
$2,
$3
)
`
type CreateSessionParams struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) error {
_, err := q.db.Exec(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
return err
}
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows
DELETE FROM sessions
WHERE expires_at <= now()
`
func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredSessions)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteSession = `-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = $1
`
func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error {
_, err := q.db.Exec(ctx, deleteSession, tokenHash)
return err
}
const getSessionUser = `-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1
AND s.expires_at > now()
`
type GetSessionUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) {
row := q.db.QueryRow(ctx, getSessionUser, tokenHash)
var i GetSessionUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
+101
View File
@@ -0,0 +1,101 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: users.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const createUser = `-- name: CreateUser :one
INSERT INTO users (
id,
username,
display_name,
password_hash
) VALUES (
$1,
$2,
$3,
$4
)
RETURNING id, username, display_name, created_at
`
type CreateUserParams struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
}
type CreateUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
row := q.db.QueryRow(ctx, createUser,
arg.ID,
arg.Username,
arg.DisplayName,
arg.PasswordHash,
)
var i CreateUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const getUser = `-- name: GetUser :one
SELECT id, username, display_name, created_at FROM users
WHERE id = $1
`
type GetUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) {
row := q.db.QueryRow(ctx, getUser, id)
var i GetUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const getUserByUsername = `-- name: GetUserByUsername :one
SELECT id, username, display_name, password_hash, created_at FROM users
WHERE username = $1
`
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
row := q.db.QueryRow(ctx, getUserByUsername, username)
var i User
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.PasswordHash,
&i.CreatedAt,
)
return i, err
}
+49
View File
@@ -0,0 +1,49 @@
package dto
import (
"mtusi2026-messenger/internal/model"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
}
type ChatResponse struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
type ChatPageResponse struct {
Items []ChatResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func (r CreateChatRequest) Validate() bool {
titleLen := utf8.RuneCountInString(r.Title)
if strings.TrimSpace(r.Title) == "" || titleLen > 100 {
return false
}
if len(r.MemberIDs) < 1 || len(r.MemberIDs) > 100 {
return false
}
return true
}
func ToChatResponse(c model.Chat) ChatResponse {
return ChatResponse{
ID: c.ID,
Title: c.Title,
MemberIDs: c.MemberIDs,
CreatedAt: c.CreatedAt,
}
}
+25
View File
@@ -0,0 +1,25 @@
package dto
type ErrorCode string
const (
ErrorCodeInvalidRequest ErrorCode = "invalid_request"
ErrorCodeUnauthorized ErrorCode = "unauthorized"
ErrorCodeNotFound ErrorCode = "not_found"
ErrorCodeConflict ErrorCode = "conflict"
ErrorCodePayloadTooLarge ErrorCode = "payload_too_large"
ErrorCodeUnsupportedMediaType ErrorCode = "unsupported_media_type"
ErrorCodeRateLimited ErrorCode = "rate_limited"
ErrorCodeUnavailable ErrorCode = "unavailable"
ErrorCodeInternalError ErrorCode = "internal_error"
)
type ErrorResponse struct {
Error Error `json:"error"`
}
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
+5
View File
@@ -0,0 +1,5 @@
package dto
type HealthResponse struct {
Status string `json:"status"`
}
+46
View File
@@ -0,0 +1,46 @@
package dto
import (
"mtusi2026-messenger/internal/model"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type CreateMessageRequest struct {
Text string `json:"text"`
}
type MessageResponse struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
SenderID uuid.UUID `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
}
type MessagePageResponse struct {
Items []MessageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func (r CreateMessageRequest) Validate() bool {
textLen := utf8.RuneCountInString(r.Text)
if strings.TrimSpace(r.Text) == "" || textLen > 4000 {
return false
}
return true
}
func ToMessageResponse(m model.Message) MessageResponse {
return MessageResponse{
ID: m.ID,
ChatID: m.ChatID,
SenderID: m.SenderID,
Text: m.Text,
CreatedAt: m.CreatedAt,
}
}
+37
View File
@@ -0,0 +1,37 @@
package dto
import (
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type UserResponse struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
}
func (r CreateUserRequest) Validate() bool {
if !usernamePattern.MatchString(r.Username) {
return false
}
displayNameLength := utf8.RuneCountInString(r.DisplayName)
if strings.TrimSpace(r.DisplayName) == "" || displayNameLength > 100 {
return false
}
return true
}
+168
View File
@@ -0,0 +1,168 @@
package handler
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
"mtusi2026-messenger/internal/httpx"
"mtusi2026-messenger/internal/middleware"
"mtusi2026-messenger/internal/service"
)
type ChatHandler struct {
service *service.ChatService
}
func NewChatHandler(service *service.ChatService) *ChatHandler {
return &ChatHandler{service: service}
}
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
var req dto.CreateChatRequest
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
return
}
if !req.Validate() {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid request body",
requestID,
)
return
}
chat, err := h.service.Create(userID, req.Title, req.MemberIDs)
switch {
case errors.Is(err, service.ErrNotChatMember):
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"caller must be a member of member_ids",
requestID,
)
return
case errors.Is(err, service.ErrDuplicateMember):
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"member_ids contains duplicates",
requestID,
)
return
case errors.Is(err, service.ErrUnknownMember):
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"member_ids contains unknown user",
requestID,
)
return
case err != nil:
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
httpx.WriteJSON(w, http.StatusCreated, dto.ToChatResponse(chat))
}
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
if err != nil {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid chat_id",
requestID,
)
return
}
chat, err := h.service.Get(userID, chatID)
switch {
case errors.Is(err, service.ErrChatNotFound):
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"chat not found",
requestID,
)
return
case err != nil:
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
httpx.WriteJSON(w, http.StatusOK, dto.ToChatResponse(chat))
}
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
limit, cursor, ok := httpx.ParsePagination(w, r, requestID)
if !ok {
return
}
chats, nextCursor, err := h.service.List(userID, limit, cursor)
switch {
case errors.Is(err, service.ErrInvalidCursor):
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid cursor",
requestID,
)
return
case err != nil:
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
items := make([]dto.ChatResponse, 0, len(chats))
for _, c := range chats {
items = append(items, dto.ToChatResponse(c))
}
httpx.WriteJSON(w, http.StatusOK, dto.ChatPageResponse{
Items: items,
NextCursor: nextCursor,
})
}
+27
View File
@@ -0,0 +1,27 @@
package handler
import (
"encoding/json"
"net/http"
"mtusi2026-messenger/internal/dto"
)
func WriteError(
w http.ResponseWriter,
status int,
code dto.ErrorCode,
message string,
requestID string,
) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(dto.ErrorResponse{
Error: dto.Error{
Code: code,
Message: message,
RequestID: requestID,
},
})
}
+59
View File
@@ -0,0 +1,59 @@
package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"mtusi2026-messenger/internal/dto"
)
const readyPingTimeout = 2 * time.Second
type Pinger interface {
Ping(ctx context.Context) error
}
type HealthHandler struct {
log *slog.Logger
db Pinger
}
func NewHealthHandler(log *slog.Logger, db Pinger) *HealthHandler {
return &HealthHandler{log: log, db: db}
}
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
Status: "ok",
})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout)
defer cancel()
if err := h.db.Ping(ctx); err != nil {
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"service unavailable",
w.Header().Get("X-Request-Id"),
)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
Status: "ok",
})
}
+142
View File
@@ -0,0 +1,142 @@
package handler
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
"mtusi2026-messenger/internal/httpx"
"mtusi2026-messenger/internal/middleware"
"mtusi2026-messenger/internal/service"
)
type MessageHandler struct {
service *service.MessageService
}
func NewMessageHandler(service *service.MessageService) *MessageHandler {
return &MessageHandler{service: service}
}
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
if err != nil {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid chat_id",
requestID,
)
return
}
var req dto.CreateMessageRequest
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
return
}
if !req.Validate() {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid request body",
requestID,
)
return
}
message, err := h.service.Create(userID, chatID, req.Text)
switch {
case errors.Is(err, service.ErrMessageChatNotFound):
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"chat not found",
requestID,
)
return
case err != nil:
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
httpx.WriteJSON(w, http.StatusCreated, dto.ToMessageResponse(message))
}
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
if err != nil {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid chat_id",
requestID,
)
return
}
limit, cursor, ok := httpx.ParsePagination(w, r, requestID)
if !ok {
return
}
messages, nextCursor, err := h.service.List(userID, chatID, limit, cursor)
switch {
case errors.Is(err, service.ErrMessageChatNotFound):
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"chat not found",
requestID,
)
return
case errors.Is(err, service.ErrInvalidCursor):
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid cursor",
requestID,
)
return
case err != nil:
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
items := make([]dto.MessageResponse, 0, len(messages))
for _, m := range messages {
items = append(items, dto.ToMessageResponse(m))
}
httpx.WriteJSON(w, http.StatusOK, dto.MessagePageResponse{
Items: items,
NextCursor: nextCursor,
})
}
+102
View File
@@ -0,0 +1,102 @@
package handler
import (
"errors"
"net/http"
"mtusi2026-messenger/internal/dto"
"mtusi2026-messenger/internal/httpx"
"mtusi2026-messenger/internal/middleware"
"mtusi2026-messenger/internal/service"
)
type UserHandler struct {
service *service.UserService
}
func NewUserHandler(service *service.UserService) *UserHandler {
return &UserHandler{service: service}
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
var req dto.CreateUserRequest
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
return
}
if !req.Validate() {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid request body",
requestID,
)
return
}
user, err := h.service.Create(req.Username, req.DisplayName)
if errors.Is(err, service.ErrUsernameTaken) {
httpx.WriteError(
w,
http.StatusConflict,
dto.ErrorCodeConflict,
"username already taken",
requestID,
)
return
}
if err != nil {
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
httpx.WriteJSON(w, http.StatusCreated, dto.UserResponse{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: user.CreatedAt,
})
}
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
user, err := h.service.GetByID(userID)
if errors.Is(err, service.ErrUserNotFound) {
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"user not found",
requestID,
)
return
}
if err != nil {
httpx.WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
return
}
httpx.WriteJSON(w, http.StatusOK, dto.UserResponse{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: user.CreatedAt,
})
}
+34
View File
@@ -0,0 +1,34 @@
package httpx
import (
"net/http"
"strconv"
"mtusi2026-messenger/internal/dto"
)
func ParsePagination(w http.ResponseWriter, r *http.Request, requestID string) (limit int, cursor *string, ok bool) {
q := r.URL.Query()
limit = 50
if raw := q.Get("limit"); raw != "" {
v, err := strconv.Atoi(raw)
if err != nil || v < 1 || v > 100 {
WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"limit must be an integer between 1 and 100",
requestID,
)
return 0, nil, false
}
limit = v
}
if raw := q.Get("cursor"); raw != "" {
cursor = &raw
}
return limit, cursor, true
}
+29
View File
@@ -0,0 +1,29 @@
package httpx
import (
"encoding/json"
"mime"
"net/http"
"mtusi2026-messenger/internal/dto"
)
func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, dst any) bool {
if ct := r.Header.Get("Content-Type"); ct != "" {
mt, _, err := mime.ParseMediaType(ct)
if err != nil || mt != "application/json" {
WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "expected application/json", requestID)
return false
}
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
return false
}
return true
}
+24
View File
@@ -0,0 +1,24 @@
package httpx
import (
"encoding/json"
"net/http"
"mtusi2026-messenger/internal/dto"
)
func WriteJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, requestID string) {
WriteJSON(w, status, dto.ErrorResponse{
Error: dto.Error{
Code: code,
Message: message,
RequestID: requestID,
},
})
}
+14
View File
@@ -0,0 +1,14 @@
package logger
import (
"log/slog"
"os"
)
func New(level slog.Level) *slog.Logger {
return slog.New(
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
}),
)
}
+65
View File
@@ -0,0 +1,65 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
"mtusi2026-messenger/internal/httpx"
"mtusi2026-messenger/internal/service"
)
type userIDContextKey struct{}
func Auth(userService *service.UserService) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := GetRequestID(r.Context())
raw := r.Header.Get("X-User-Id")
if raw == "" {
httpx.WriteError(
w,
http.StatusUnauthorized,
dto.ErrorCodeUnauthorized,
"missing X-User-Id header",
requestID,
)
return
}
userID, err := uuid.Parse(raw)
if err != nil {
httpx.WriteError(
w,
http.StatusUnauthorized,
dto.ErrorCodeUnauthorized,
"invalid X-User-Id header",
requestID,
)
return
}
if _, err := userService.GetByID(userID); err != nil {
httpx.WriteError(
w,
http.StatusUnauthorized,
dto.ErrorCodeUnauthorized,
"unknown user",
requestID,
)
return
}
ctx := context.WithValue(r.Context(), userIDContextKey{}, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func GetUserID(ctx context.Context) uuid.UUID {
id, _ := ctx.Value(userIDContextKey{}).(uuid.UUID)
return id
}
+41
View File
@@ -0,0 +1,41 @@
package middleware
import (
"net/http"
"mtusi2026-messenger/internal/dto"
"mtusi2026-messenger/internal/httpx"
)
func ConcurrencyLimit(max int) func(http.Handler) http.Handler {
if max <= 0 {
return func(next http.Handler) http.Handler {
return next
}
}
slots := make(chan struct{}, max)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case slots <- struct{}{}:
defer func() {
<-slots
}()
next.ServeHTTP(w, r)
default:
w.Header().Set("Retry-After", "1")
httpx.WriteError(
w,
http.StatusTooManyRequests,
dto.ErrorCodeRateLimited,
"too many requests",
GetRequestID(r.Context()),
)
}
})
}
}
+49
View File
@@ -0,0 +1,49 @@
package middleware
import (
"log/slog"
"net/http"
"time"
)
type responseWriter struct {
http.ResponseWriter
status int
}
func (w *responseWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func Logging(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
writer := &responseWriter{
ResponseWriter: w,
status: http.StatusOK,
}
next.ServeHTTP(writer, r)
level := slog.LevelInfo
switch {
case writer.status >= 500:
level = slog.LevelError
case writer.status >= 400:
level = slog.LevelWarn
}
log.Log(r.Context(), level, "http request",
"request_id", GetRequestID(r.Context()),
"method", r.Method,
"path", r.URL.Path,
"status", writer.status,
"duration_ms", time.Since(start).Milliseconds(),
)
})
}
}
+30
View File
@@ -0,0 +1,30 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
)
type requestIDContextKey struct{}
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get("X-Request-Id")
if requestID == "" {
requestID = uuid.NewString()
}
w.Header().Set("X-Request-Id", requestID)
ctx := context.WithValue(r.Context(), requestIDContextKey{}, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetRequestID(ctx context.Context) string {
id, _ := ctx.Value(requestIDContextKey{}).(string)
return id
}
+14
View File
@@ -0,0 +1,14 @@
package model
import (
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
MemberIDs []uuid.UUID
CreatedAt time.Time
}
+15
View File
@@ -0,0 +1,15 @@
package model
import (
"time"
"github.com/google/uuid"
)
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package model
import (
"time"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
+25
View File
@@ -0,0 +1,25 @@
package postgres
import (
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
const (
CodeUniqueViolation = "23505"
CodeForeignKeyViolation = "23503"
CodeCheckViolation = "23514"
)
func ErrCode(err error) string {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
return pgErr.Code
}
return ""
}
func IsNotFound(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
+34
View File
@@ -0,0 +1,34 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func New(ctx context.Context, url string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
}
cfg.MaxConns = 10
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
+109
View File
@@ -0,0 +1,109 @@
package service
import (
"errors"
"slices"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/model"
"mtusi2026-messenger/internal/store"
)
var (
ErrChatNotFound = errors.New("chat not found")
ErrNotChatMember = errors.New("caller must be a member of member_ids")
ErrDuplicateMember = errors.New("member_ids contains duplicates")
ErrUnknownMember = errors.New("member_ids contains unknown user")
)
type ChatService struct {
store *store.Memory
}
func NewChatService(store *store.Memory) *ChatService {
return &ChatService{store: store}
}
func (s *ChatService) Create(
userID uuid.UUID,
title string,
memberIDs []uuid.UUID,
) (model.Chat, error) {
if !slices.Contains(memberIDs, userID) {
return model.Chat{}, ErrNotChatMember
}
chat, err := s.store.CreateChat(title, memberIDs)
switch {
case errors.Is(err, store.ErrDuplicateMember):
return model.Chat{}, ErrDuplicateMember
case errors.Is(err, store.ErrUnknownMember):
return model.Chat{}, ErrUnknownMember
case err != nil:
return model.Chat{}, err
}
return chat, nil
}
func (s *ChatService) Get(
userID uuid.UUID,
chatID uuid.UUID,
) (model.Chat, error) {
chat, err := s.store.GetChat(chatID, userID)
if errors.Is(err, store.ErrNotFound) {
return model.Chat{}, ErrChatNotFound
}
if err != nil {
return model.Chat{}, err
}
return chat, nil
}
func (s *ChatService) List(
userID uuid.UUID,
limit int,
cursor *string,
) ([]model.Chat, *string, error) {
var afterCreatedAt *time.Time
var afterID *uuid.UUID
if cursor != nil {
decoded, err := decodeCursor(*cursor)
if err != nil {
return nil, nil, ErrInvalidCursor
}
afterCreatedAt = &decoded.CreatedAt
afterID = &decoded.ID
}
chats, hasMore, err := s.store.ListChats(
userID,
afterCreatedAt,
afterID,
limit,
)
if errors.Is(err, store.ErrInvalidCursor) {
return nil, nil, ErrInvalidCursor
}
if err != nil {
return nil, nil, err
}
var next *string
if hasMore && len(chats) > 0 {
last := chats[len(chats)-1]
c := encodeCursor(Cursor{
CreatedAt: last.CreatedAt,
ID: last.ID,
})
next = &c
}
return chats, next, nil
}
+40
View File
@@ -0,0 +1,40 @@
package service
import (
"encoding/base64"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
)
var ErrInvalidCursor = errors.New("invalid cursor")
type Cursor struct {
CreatedAt time.Time `json:"created_at"`
ID uuid.UUID `json:"id"`
}
func encodeCursor(cursor Cursor) string {
data, _ := json.Marshal(cursor)
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(raw string) (Cursor, error) {
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalidCursor
}
var cursor Cursor
if err := json.Unmarshal(data, &cursor); err != nil {
return Cursor{}, ErrInvalidCursor
}
if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() {
return Cursor{}, ErrInvalidCursor
}
return cursor, nil
}
+87
View File
@@ -0,0 +1,87 @@
package service
import (
"errors"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/model"
"mtusi2026-messenger/internal/store"
)
var ErrMessageChatNotFound = errors.New("chat not found")
type MessageService struct {
store *store.Memory
}
func NewMessageService(store *store.Memory) *MessageService {
return &MessageService{store: store}
}
func (s *MessageService) Create(
userID uuid.UUID,
chatID uuid.UUID,
text string,
) (model.Message, error) {
message, err := s.store.CreateMessage(chatID, userID, text)
if errors.Is(err, store.ErrNotFound) {
return model.Message{}, ErrMessageChatNotFound
}
if err != nil {
return model.Message{}, err
}
return message, nil
}
func (s *MessageService) List(
userID uuid.UUID,
chatID uuid.UUID,
limit int,
cursor *string,
) ([]model.Message, *string, error) {
var afterCreatedAt *time.Time
var afterID *uuid.UUID
if cursor != nil {
decoded, err := decodeCursor(*cursor)
if err != nil {
return nil, nil, ErrInvalidCursor
}
afterCreatedAt = &decoded.CreatedAt
afterID = &decoded.ID
}
messages, hasMore, err := s.store.ListMessages(
chatID,
userID,
afterCreatedAt,
afterID,
limit,
)
if errors.Is(err, store.ErrNotFound) {
return nil, nil, ErrMessageChatNotFound
}
if errors.Is(err, store.ErrInvalidCursor) {
return nil, nil, ErrInvalidCursor
}
if err != nil {
return nil, nil, err
}
var next *string
if hasMore && len(messages) > 0 {
last := messages[len(messages)-1]
c := encodeCursor(Cursor{
CreatedAt: last.CreatedAt,
ID: last.ID,
})
next = &c
}
return messages, next, nil
}
+47
View File
@@ -0,0 +1,47 @@
package service
import (
"errors"
"github.com/google/uuid"
"mtusi2026-messenger/internal/model"
"mtusi2026-messenger/internal/store"
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUsernameTaken = errors.New("username already taken")
)
type UserService struct {
store *store.Memory
}
func NewUserService(store *store.Memory) *UserService {
return &UserService{store: store}
}
func (s *UserService) Create(username, displayName string) (model.User, error) {
user, err := s.store.CreateUser(username, displayName)
if errors.Is(err, store.ErrConflict) {
return model.User{}, ErrUsernameTaken
}
if err != nil {
return model.User{}, err
}
return user, nil
}
func (s *UserService) GetByID(id uuid.UUID) (model.User, error) {
user, err := s.store.GetUser(id)
if errors.Is(err, store.ErrNotFound) {
return model.User{}, ErrUserNotFound
}
if err != nil {
return model.User{}, err
}
return user, nil
}
+236
View File
@@ -0,0 +1,236 @@
package store
import (
"errors"
"slices"
"sort"
"sync"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/model"
)
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrDuplicateMember = errors.New("duplicate member id")
ErrUnknownMember = errors.New("unknown member id")
ErrInvalidCursor = errors.New("invalid cursor")
)
type Memory struct {
mu sync.RWMutex
users map[uuid.UUID]model.User
usersByUsername map[string]uuid.UUID
chats map[uuid.UUID]model.Chat
messages map[uuid.UUID]model.Message
chatMessages map[uuid.UUID][]uuid.UUID
}
func New() *Memory {
return &Memory{
users: make(map[uuid.UUID]model.User),
usersByUsername: make(map[string]uuid.UUID),
chats: make(map[uuid.UUID]model.Chat),
messages: make(map[uuid.UUID]model.Message),
chatMessages: make(map[uuid.UUID][]uuid.UUID),
}
}
func (m *Memory) CreateUser(username, displayName string) (model.User, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.usersByUsername[username]; exists {
return model.User{}, ErrConflict
}
user := model.User{
ID: uuid.New(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC(),
}
m.users[user.ID] = user
m.usersByUsername[user.Username] = user.ID
return user, nil
}
func (m *Memory) GetUser(id uuid.UUID) (model.User, error) {
m.mu.RLock()
defer m.mu.RUnlock()
user, exists := m.users[id]
if !exists {
return model.User{}, ErrNotFound
}
return user, nil
}
func (m *Memory) CreateChat(title string, memberIDs []uuid.UUID) (model.Chat, error) {
m.mu.Lock()
defer m.mu.Unlock()
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, dup := seen[id]; dup {
return model.Chat{}, ErrDuplicateMember
}
seen[id] = struct{}{}
if _, exists := m.users[id]; !exists {
return model.Chat{}, ErrUnknownMember
}
}
chat := model.Chat{
ID: uuid.New(),
Title: title,
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
CreatedAt: time.Now().UTC(),
}
m.chats[chat.ID] = chat
return chat, nil
}
func (m *Memory) GetChat(id uuid.UUID, userID uuid.UUID) (model.Chat, error) {
m.mu.RLock()
defer m.mu.RUnlock()
chat, exists := m.chats[id]
if !exists || !slices.Contains(chat.MemberIDs, userID) {
return model.Chat{}, ErrNotFound
}
chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...)
return chat, nil
}
func (m *Memory) ListChats(
userID uuid.UUID,
afterCreatedAt *time.Time,
afterID *uuid.UUID,
limit int,
) ([]model.Chat, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
chats := make([]model.Chat, 0)
for _, c := range m.chats {
if slices.Contains(c.MemberIDs, userID) {
c.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...)
chats = append(chats, c)
}
}
sort.Slice(chats, func(i, j int) bool {
if !chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
}
return chats[i].ID.String() < chats[j].ID.String()
})
start := 0
if afterCreatedAt != nil && afterID != nil {
start = sort.Search(len(chats), func(i int) bool {
chat := chats[i]
return chat.CreatedAt.After(*afterCreatedAt) ||
(chat.CreatedAt.Equal(*afterCreatedAt) &&
chat.ID.String() > afterID.String())
})
}
end := start + limit
hasMore := end < len(chats)
if end > len(chats) {
end = len(chats)
}
return chats[start:end], hasMore, nil
}
func (m *Memory) CreateMessage(
chatID uuid.UUID,
senderID uuid.UUID,
text string,
) (model.Message, error) {
m.mu.Lock()
defer m.mu.Unlock()
chat, exists := m.chats[chatID]
if !exists || !slices.Contains(chat.MemberIDs, senderID) {
return model.Message{}, ErrNotFound
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC(),
}
m.messages[message.ID] = message
m.chatMessages[chatID] = append(m.chatMessages[chatID], message.ID)
return message, nil
}
func (m *Memory) ListMessages(
chatID uuid.UUID,
userID uuid.UUID,
afterCreatedAt *time.Time,
afterID *uuid.UUID,
limit int,
) ([]model.Message, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
chat, exists := m.chats[chatID]
if !exists || !slices.Contains(chat.MemberIDs, userID) {
return nil, false, ErrNotFound
}
ids := m.chatMessages[chatID]
messages := make([]model.Message, 0, len(ids))
for _, id := range ids {
messages = append(messages, m.messages[id])
}
sort.Slice(messages, func(i, j int) bool {
if !messages[i].CreatedAt.Equal(messages[j].CreatedAt) {
return messages[i].CreatedAt.Before(messages[j].CreatedAt)
}
return messages[i].ID.String() < messages[j].ID.String()
})
start := 0
if afterCreatedAt != nil && afterID != nil {
start = sort.Search(len(messages), func(i int) bool {
msg := messages[i]
return msg.CreatedAt.After(*afterCreatedAt) ||
(msg.CreatedAt.Equal(*afterCreatedAt) &&
msg.ID.String() > afterID.String())
})
}
end := start + limit
hasMore := end < len(messages)
if end > len(messages) {
end = len(messages)
}
return messages[start:end], hasMore, nil
}
+31
View File
@@ -0,0 +1,31 @@
version: "2"
sql:
- engine: "postgresql"
queries: "db/queries"
schema: "db/migrations"
gen:
go:
package: "db"
out: "internal/db"
sql_package: "pgx/v5"
emit_interface: true
emit_empty_slices: true
emit_pointers_for_null_types: true
overrides:
- db_type: "uuid"
go_type: "github.com/google/uuid.UUID"
- db_type: "uuid"
nullable: true
go_type:
import: "github.com/google/uuid"
type: "UUID"
pointer: true
- db_type: "timestamptz"
go_type: "time.Time"
- db_type: "timestamptz"
nullable: true
go_type:
import: "time"
type: "Time"
pointer: true
+135
View File
@@ -0,0 +1,135 @@
//go:build contract
package studenttests_test
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
func TestInvalidJSON(t *testing.T) {
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, []byte(`{"username": "broken",`))
requireStatus(t, resp, http.StatusBadRequest)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeInvalidRequest {
t.Errorf("expected code %q, got %q", dto.ErrorCodeInvalidRequest, apiErr.Error.Code)
}
}
func TestForeignChat(t *testing.T) {
user1 := createUser(t)
user2 := createUser(t)
user3 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.ID, nil)
requireStatus(t, resp, http.StatusNotFound)
resp = sendMessage(t, user3, chat.ID, "should not land")
requireStatus(t, resp, http.StatusNotFound)
}
func TestEmptyMessage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
for _, text := range []string{"", " ", "\t\n"} {
resp := sendMessage(t, user, chat.ID, text)
requireStatus(t, resp, http.StatusBadRequest)
}
}
func TestDuplicateUsername(t *testing.T) {
user := createUser(t)
body, err := json.Marshal(map[string]string{
"username": user.Username,
"display_name": "Someone else",
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, body)
requireStatus(t, resp, http.StatusConflict)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeConflict {
t.Errorf("expected code %q, got %q", dto.ErrorCodeConflict, apiErr.Error.Code)
}
}
func TestPagination(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
const total = 25
const pageSize = 4
sent := make(map[string]bool, total)
for i := 0; i < total; i++ {
resp := sendMessage(t, user, chat.ID, "msg")
requireStatus(t, resp, http.StatusCreated)
var msg dto.MessageResponse
mustDecode(t, resp, &msg)
sent[msg.ID.String()] = true
}
seen := make(map[string]bool, total)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=" + strconv.Itoa(pageSize)
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := doRequest(t, http.MethodGet, path, user.ID, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
pages++
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id across pages: %s", id)
}
seen[id] = true
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
if pages > total {
t.Fatalf("too many pages: got %d, expected at most %d", pages, total)
}
}
if len(seen) != total {
t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen))
}
for id := range sent {
if !seen[id] {
t.Fatalf("message %s sent but never seen while paginating", id)
}
}
}
+198
View File
@@ -0,0 +1,198 @@
package studenttests_test
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
var baseURL = flag.String("base-url", "http://127.0.0.1:8080", "base URL of the running server")
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
},
}
func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
if err != nil {
t.Fatalf("build request: %v", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actorID != uuid.Nil {
req.Header.Set("X-User-Id", actorID.String())
}
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("%s %s: request failed: %v", method, path, err)
}
return resp
}
func mustDecode(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body %q: %v", data, err)
}
}
func requireStatus(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf(
"expected status %d, got %d, body: %s",
expected,
resp.StatusCode,
data,
)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Errorf("missing X-Request-Id header")
}
}
func createUser(t *testing.T) dto.UserResponse {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/users",
uuid.Nil,
body,
)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
return u
}
func createChat(
t *testing.T,
creator dto.UserResponse,
memberIDs ...uuid.UUID,
) dto.ChatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{
"title": "Test chat " + uuid.NewString()[:8],
"member_ids": memberIDs,
})
if err != nil {
t.Fatalf("marshal chat: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/chats",
creator.ID,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor dto.UserResponse,
chatID uuid.UUID,
text string,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
return doRequest(
t,
http.MethodPost,
fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()),
actor.ID,
body,
)
}
func sendLoadMessage(
actor dto.UserResponse,
chatID uuid.UUID,
text string,
) (*http.Response, error) {
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Id", actor.ID.String())
return httpClient.Do(req)
}
+138
View File
@@ -0,0 +1,138 @@
//go:build load
package studenttests_test
import (
"flag"
"io"
"net/http"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
workers = flag.Int("workers", 20, "number of concurrent workers")
duration = flag.Duration("duration", 5*time.Second, "test duration")
rate = flag.Int("rate", 20, "maximum requests per second per worker")
)
func TestLoad(t *testing.T) {
var (
statuses = make(map[int]int64)
requestErrors int64
latencies []time.Duration
statusMu sync.Mutex
latencyMu sync.Mutex
wg sync.WaitGroup
)
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
start := time.Now()
deadline := start.Add(*duration)
interval := time.Second / time.Duration(*rate)
for worker := 0; worker < *workers; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for time.Now().Before(deadline) {
<-ticker.C
if time.Now().After(deadline) {
return
}
requestStart := time.Now()
resp, err := sendLoadMessage(
actor,
chat.ID,
"load-msg",
)
latency := time.Since(requestStart)
if err != nil {
if atomic.CompareAndSwapInt64(&requestErrors, 0, 1) {
t.Logf("first transport error: %v", err)
}
atomic.AddInt64(&requestErrors, 1)
continue
}
statusMu.Lock()
statuses[resp.StatusCode]++
statusMu.Unlock()
if resp.StatusCode == http.StatusCreated {
latencyMu.Lock()
latencies = append(latencies, latency)
latencyMu.Unlock()
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}(worker)
}
wg.Wait()
elapsed := time.Since(start)
var total int64
for _, count := range statuses {
total += count
}
total += requestErrors
t.Logf("duration: %.3fs", elapsed.Seconds())
t.Logf("workers: %d", *workers)
t.Logf("rate per worker: %d req/s", *rate)
t.Logf("target rate: %d req/s", *workers**rate)
t.Logf("total requests: %d", total)
for status, count := range statuses {
t.Logf("HTTP %d: %d", status, count)
}
t.Logf("request errors: %d", requestErrors)
successful := statuses[http.StatusCreated]
t.Logf("successful RPS: %.2f",
float64(successful)/elapsed.Seconds(),
)
if len(latencies) > 0 {
sort.Slice(latencies, func(i, j int) bool {
return latencies[i] < latencies[j]
})
t.Logf("successful latency p50: %s", percentile(latencies, 0.50))
t.Logf("successful latency p95: %s", percentile(latencies, 0.95))
t.Logf("successful latency p99: %s", percentile(latencies, 0.99))
}
}
func percentile(values []time.Duration, p float64) time.Duration {
index := int(float64(len(values)-1) * p)
return values[index]
}
+100
View File
@@ -0,0 +1,100 @@
//go:build race
package studenttests_test
import (
"net/http"
"sync"
"testing"
"mtusi2026-messenger/internal/dto"
)
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
var wg sync.WaitGroup
var mu sync.Mutex
sentIDs := make(map[string]bool, total)
start := make(chan struct{})
for worker := 0; worker < clients; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
<-start
for i := 0; i < messagesPerClient; i++ {
resp := sendMessage(t, actor, chat.ID, "race-msg")
if resp.StatusCode != http.StatusCreated {
t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode)
resp.Body.Close()
continue
}
var m dto.MessageResponse
mustDecode(t, resp, &m)
mu.Lock()
sentIDs[m.ID.String()] = true
mu.Unlock()
}
}(worker)
}
close(start)
wg.Wait()
if t.Failed() {
t.Fatal("one or more send requests failed, see errors above")
}
if len(sentIDs) != total {
t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs))
}
seen := make(map[string]bool, total)
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100"
resp := doRequest(t, http.MethodGet, path, user1.ID, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
if page.NextCursor != nil {
t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total)
}
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id in history: %s", id)
}
if !sentIDs[id] {
t.Fatalf("message %s in history was never sent by this test", id)
}
seen[id] = true
}
if len(seen) != total {
t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen))
}
t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted",
clients, total, len(seen))
}
+17
View File
@@ -0,0 +1,17 @@
LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \
$(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \
$(if $(LOAD_RATE),-rate=$(LOAD_RATE),)
.PHONY: help-go contract-go race-go load-go
help-go:
@echo "contract-go: student contract tests; race-go: concurrency test with -race; load-go: Go load test"
contract-go:
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
race-go:
go test -tags=race ./student-tests/... -race -v -args -base-url=$(BASE_URL)
load-go:
go test -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS)
+21
View File
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>MTUSI Messenger API</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script>
window.onload = () => {
SwaggerUIBundle({
url: "/contracts/openapi.json",
dom_id: "#swagger-ui"
});
};
</script>
</body>
</html>