feat: lab4 - S3 attachments, image validation, failover

This commit is contained in:
2026-11-11 21:42:08 +03:00
parent 312131c344
commit 9fc37b0d8a
18 changed files with 1050 additions and 59 deletions
+49 -14
View File
@@ -1,27 +1,62 @@
// Package config reads the runtime configuration shared by every API replica.
package config
import "os"
import (
"log"
"os"
"strconv"
"time"
)
const (
defaultPort = "8080"
defaultSessionTTL = time.Hour
defaultIdempotencyTTL = 24 * time.Hour
defaultDrainDelay = 3 * time.Second
)
// Config is the complete runtime configuration of one API process.
type Config struct {
InstanceID string
Port string
DatabaseURL string
InstanceID string
Port string
DatabaseURL string
SessionTTL time.Duration
IdempotencyTTL time.Duration
DrainDelay time.Duration
}
// Load reads the environment; DATABASE_URL is the only mandatory value.
func Load() *Config {
cfg := &Config{
InstanceID: os.Getenv("APP_INSTANCE_ID"),
Port: os.Getenv("APP_PORT"),
DatabaseURL: os.Getenv("DATABASE_URL"),
}
if cfg.InstanceID == "" {
cfg.InstanceID = "api"
}
if cfg.Port == "" {
cfg.Port = "8080"
InstanceID: valueOr(os.Getenv("APP_INSTANCE_ID"), "api"),
Port: valueOr(os.Getenv("APP_PORT"), defaultPort),
DatabaseURL: os.Getenv("DATABASE_URL"),
SessionTTL: durationOr("SESSION_TTL_SECONDS", defaultSessionTTL),
IdempotencyTTL: durationOr("IDEMPOTENCY_TTL_SECONDS", defaultIdempotencyTTL),
DrainDelay: durationOr("DRAIN_DELAY_SECONDS", defaultDrainDelay),
}
if cfg.DatabaseURL == "" {
panic("APP_INSTANCE_ID/APP_PORT optional; DATABASE_URL is required")
log.Fatal("config: DATABASE_URL is required")
}
return cfg
}
func valueOr(raw, fallback string) string {
if raw == "" {
return fallback
}
return raw
}
func durationOr(env string, fallback time.Duration) time.Duration {
raw := os.Getenv(env)
if raw == "" {
return fallback
}
seconds, err := strconv.Atoi(raw)
if err != nil || seconds <= 0 {
log.Printf("config: ignoring invalid %s=%q, using %s", env, raw, fallback)
return fallback
}
return time.Duration(seconds) * time.Second
}
+47
View File
@@ -0,0 +1,47 @@
// Package cursor implements the opaque keyset cursor used by paged collections.
package cursor
import (
"encoding/base64"
"errors"
"strings"
"time"
"mtusi2026lab3/internal/domain"
"mtusi2026lab3/internal/validate"
)
// ErrInvalid marks a cursor that cannot be decoded or belongs to another resource.
var ErrInvalid = errors.New("invalid cursor")
// Value is a decoded (created_at, id) position bound to one collection scope.
type Value struct {
CreatedAt time.Time
ID string
}
// Encode serialises a position so clients can replay it but not forge a new one.
func Encode(scope string, createdAt time.Time, id string) string {
raw := scope + "|" + createdAt.UTC().Format(domain.TimeFormat) + "|" + id
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
// Decode validates the cursor and rejects one issued for another collection.
func Decode(encoded, scope string) (Value, error) {
raw, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
return Value{}, ErrInvalid
}
parts := strings.Split(string(raw), "|")
if len(parts) != 3 || parts[0] != scope {
return Value{}, ErrInvalid
}
createdAt, err := time.Parse(domain.TimeFormat, parts[1])
if err != nil {
return Value{}, ErrInvalid
}
if !validate.UUID(parts[2]) {
return Value{}, ErrInvalid
}
return Value{CreatedAt: createdAt.UTC(), ID: parts[2]}, nil
}
+16
View File
@@ -0,0 +1,16 @@
package domain
import "errors"
// ErrNotFound covers both "missing" and "not visible to this user", so the API
// never reveals that someone else's object exists.
var ErrNotFound = errors.New("object not found")
// ErrUsernameTaken means the username uniqueness constraint was violated.
var ErrUsernameTaken = errors.New("username already taken")
// ErrIdempotencyConflict means the same key was reused with a different body.
var ErrIdempotencyConflict = errors.New("idempotency key reused with another body")
// ErrUnknownMembers means member_ids references users that do not exist.
var ErrUnknownMembers = errors.New("unknown chat members")
+67
View File
@@ -0,0 +1,67 @@
// Package domain holds the JSON shapes of the public contract.
package domain
import (
"encoding/json"
"time"
)
// TimeFormat is the RFC 3339 UTC representation used by every response.
const TimeFormat = "2006-01-02T15:04:05.000000Z"
// Timestamp marshals with stable microsecond precision and a trailing Z.
type Timestamp struct {
time.Time
}
// NewTimestamp keeps the precision PostgreSQL stores and normalises to UTC.
func NewTimestamp(t time.Time) Timestamp {
return Timestamp{Time: t.UTC().Round(time.Microsecond)}
}
func (t Timestamp) MarshalJSON() ([]byte, error) {
return json.Marshal(t.UTC().Format(TimeFormat))
}
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Timestamp `json:"created_at"`
}
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Timestamp `json:"expires_at"`
User User `json:"user"`
}
type Health struct {
Status string `json:"status"`
}
+35 -6
View File
@@ -1,16 +1,45 @@
// Package ident produces opaque identifiers: request ids, session tokens and UUIDv4 values.
package ident
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
const tokenBytes = 32
const (
tokenBytes = 32
requestIDSize = 16
)
// NewToken returns a 64 character hex session token (256 bits of entropy).
func NewToken() string {
return hex.EncodeToString(randomBytes(tokenBytes))
}
// NewRequestID returns a short opaque request identifier.
func NewRequestID() string {
return hex.EncodeToString(randomBytes(requestIDSize))
}
// NewUUID returns a RFC 4122 version 4 UUID string.
func NewUUID() string {
buf := randomBytes(16)
buf[6] = (buf[6] & 0x0f) | 0x40
buf[8] = (buf[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", buf[0:4], buf[4:6], buf[6:8], buf[8:10], buf[10:16])
}
func randomBytes(size int) []byte {
buf := make([]byte, size)
if _, err := rand.Read(buf); err != nil {
panic("crypto/rand unavailable: " + err.Error())
}
return buf
}
func GenerateToken() string {
buf := make([]byte, tokenBytes)
if _, err := rand.Read(buf); err != nil {
panic(err)
}
return hex.EncodeToString(buf)
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
+66
View File
@@ -0,0 +1,66 @@
package s3
import (
"context"
"errors"
"io"
"os"
"strings"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func NewClient() (*minio.Client, string, error) {
endpoint := os.Getenv("S3_ENDPOINT")
accessKey := os.Getenv("S3_ACCESS_KEY")
secretKey := os.Getenv("S3_SECRET_KEY")
bucket := os.Getenv("S3_BUCKET")
if endpoint == "" || accessKey == "" || secretKey == "" || bucket == "" {
return nil, "", errors.New("S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEY, S3_BUCKET must be set")
}
endpoint = strings.TrimPrefix(endpoint, "http://")
endpoint = strings.TrimPrefix(endpoint, "https://")
client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: false,
})
if err != nil {
return nil, "", err
}
return client, bucket, nil
}
func EnsureBucket(ctx context.Context, client *minio.Client, bucket string) error {
exists, err := client.BucketExists(ctx, bucket)
if err != nil {
return err
}
if !exists {
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
}
return nil
}
func UploadFile(ctx context.Context, client *minio.Client, bucket, key string, data io.Reader, size int64, contentType string) error {
_, err := client.PutObject(ctx, bucket, key, data, size, minio.PutObjectOptions{
ContentType: contentType,
})
return err
}
func DownloadFile(ctx context.Context, client *minio.Client, bucket, key string) (io.ReadCloser, error) {
obj, err := client.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
return obj, nil
}
func DeleteFile(ctx context.Context, client *minio.Client, bucket, key string) error {
return client.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{})
}
+51
View File
@@ -0,0 +1,51 @@
// Package store is the only layer that talks to PostgreSQL.
package store
import (
"context"
"database/sql"
"time"
_ "github.com/lib/pq"
)
const (
maxOpenConns = 20
maxIdleConns = 10
connMaxLifetime = 5 * time.Minute
pingTimeout = 2 * time.Second
)
// Store wraps the shared PostgreSQL connection pool.
type Store struct {
db *sql.DB
}
// Open creates the pool; it does not require the database to be reachable yet.
func Open(databaseURL string) (*Store, error) {
db, err := sql.Open("postgres", databaseURL)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(maxOpenConns)
db.SetMaxIdleConns(maxIdleConns)
db.SetConnMaxLifetime(connMaxLifetime)
return &Store{db: db}, nil
}
// Close releases the pool.
func (s *Store) Close() error {
return s.db.Close()
}
// Ping reports whether the database answers within a short budget; readiness uses it.
func (s *Store) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, pingTimeout)
defer cancel()
return s.db.PingContext(ctx)
}
// scanTime normalises timestamps returned by the driver.
func utc(t time.Time) time.Time {
return t.UTC()
}
+76
View File
@@ -0,0 +1,76 @@
package store
import (
"context"
"database/sql"
"errors"
"github.com/lib/pq"
"mtusi2026lab3/internal/domain"
"mtusi2026lab3/internal/ident"
)
// UserRecord is a user together with the password hash used only for login.
type UserRecord struct {
User domain.User
PasswordHash string
}
const userColumns = `id::text, username, display_name, created_at`
// CreateUser inserts a new user; a duplicate username maps to domain.ErrUsernameTaken.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) {
user := domain.User{ID: ident.NewUUID(), Username: username, DisplayName: displayName}
row := s.db.QueryRowContext(ctx,
`INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1::uuid, $2, $3, $4)
RETURNING `+userColumns,
user.ID, user.Username, user.DisplayName, passwordHash)
if err := scanUser(row, &user); err != nil {
if isUniqueViolation(err) {
return domain.User{}, domain.ErrUsernameTaken
}
return domain.User{}, err
}
return user, nil
}
// UserByUsername returns the credential record used by Basic authentication.
func (s *Store) UserByUsername(ctx context.Context, username string) (UserRecord, error) {
row := s.db.QueryRowContext(ctx,
`SELECT `+userColumns+`, password_hash FROM users WHERE username = $1`, username)
var record UserRecord
if err := scanUser(row, &record.User); err != nil {
return UserRecord{}, err
}
if err := row.Scan(&record.User.ID, &record.User.Username, &record.User.DisplayName,
&record.User.CreatedAt.Time, &record.PasswordHash); err != nil {
return UserRecord{}, err
}
return record, nil
}
// UserByID resolves the owner of a valid session.
func (s *Store) UserByID(ctx context.Context, id string) (domain.User, error) {
var user domain.User
row := s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1::uuid`, id)
if err := scanUser(row, &user); err != nil {
return domain.User{}, err
}
return user, nil
}
func scanUser(row *sql.Row, user *domain.User) error {
var created sql.NullTime
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &created); err != nil {
return err
}
user.CreatedAt = domain.NewTimestamp(created.Time)
return nil
}
func isUniqueViolation(err error) bool {
var pqErr *pq.Error
return errors.As(err, &pqErr) && pqErr.Code == "23505"
}
+87
View File
@@ -0,0 +1,87 @@
// Package validate implements the field rules stated in contracts/README.md.
package validate
import (
"strings"
"unicode/utf8"
)
const (
UsernameMinLen = 3
UsernameMaxLen = 32
DisplayNameMaxLen = 100
PasswordMinLen = 12
PasswordMaxLen = 128
TitleMaxLen = 100
MessageMaxRunes = 4000
)
// UUID reports whether s has the canonical 8-4-4-4-12 hex shape.
func UUID(s string) bool {
if len(s) != 36 {
return false
}
for i := 0; i < len(s); i++ {
switch i {
case 8, 13, 18, 23:
if s[i] != '-' {
return false
}
default:
if !isHex(s[i]) {
return false
}
}
}
return true
}
// Username enforces ^[a-z0-9_]{3,32}$.
func Username(s string) bool {
if len(s) < UsernameMinLen || len(s) > UsernameMaxLen {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
continue
}
return false
}
return true
}
// NonBlank requires at least one non-whitespace code point.
func NonBlank(s string) bool {
return strings.TrimSpace(s) != ""
}
// DisplayName allows 1..100 code points and rejects whitespace-only values.
func DisplayName(s string) bool {
return NonBlank(s) && RuneLen(s) <= DisplayNameMaxLen
}
// Password checks the 12..128 code point range; Basic auth carries UTF-8.
func Password(s string) bool {
n := RuneLen(s)
return n >= PasswordMinLen && n <= PasswordMaxLen
}
// Title allows 1..100 code points and rejects whitespace-only values.
func Title(s string) bool {
return NonBlank(s) && RuneLen(s) <= TitleMaxLen
}
// MessageText allows 1..4000 code points and rejects whitespace-only values.
func MessageText(s string) bool {
return NonBlank(s) && RuneLen(s) <= MessageMaxRunes
}
// RuneLen counts Unicode code points, not bytes.
func RuneLen(s string) int {
return utf8.RuneCountInString(s)
}
func isHex(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}