ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions

Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
2026-12-02 23:08:27 +03:00
parent 20afc2c790
commit 2f2047909f
182 changed files with 15169 additions and 90 deletions
+202
View File
@@ -0,0 +1,202 @@
package app
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/joho/godotenv"
goredis "github.com/redis/go-redis/v9"
"gavrilenko-sxdees/lab7/internal/config"
"gavrilenko-sxdees/lab7/internal/openbao"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/outbox"
"gavrilenko-sxdees/lab7/internal/postgres"
"gavrilenko-sxdees/lab7/internal/redis"
s3store "gavrilenko-sxdees/lab7/internal/s3"
"gavrilenko-sxdees/lab7/internal/service"
"gavrilenko-sxdees/lab7/internal/telemetry"
"gavrilenko-sxdees/lab7/internal/tlslisten"
)
func Run() error {
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
return err
}
cfg := config.Load()
baoCtx, baoCancel := context.WithTimeout(context.Background(), 8*time.Second)
if err := openbao.VerifyAppRole(baoCtx, "api"); err != nil && os.Getenv("BAO_REQUIRED") != "false" {
baoCancel()
return fmt.Errorf("openbao service auth: %w", err)
}
baoCancel()
serviceName := os.Getenv("OTEL_SERVICE_NAME")
if serviceName == "" {
serviceName = "messenger-api"
}
log, shutdownTelemetry, err := telemetry.Init(context.Background(), serviceName)
if err != nil {
return err
}
defer shutdownTelemetry()
log = log.With("instance_id", cfg.Server.InstanceID)
dbURL, err := cfg.Database.URL()
if err != nil {
log.Error("read database url", "error", err)
return err
}
pool, err := postgres.New(context.Background(), dbURL)
if err != nil {
log.Error("connect to database", "error", err)
return err
}
defer pool.Close()
telemetry.RegisterPoolObservers(pool, false)
queries := db.New(pool)
var rdb *goredis.Client
if cfg.UseCache() {
cacheURL, err := cfg.Redis.URL()
if err != nil {
log.Error("read redis url", "error", err)
return err
}
rdb, err = redis.New(context.Background(), log, cacheURL)
if err != nil {
log.Error("create redis client", "error", err)
return err
}
defer rdb.Close()
}
log.Info("session store configured", "store", cfg.SessionStore)
s3Client, err := s3store.New(context.Background(), cfg.S3, log)
if err != nil {
log.Error("create s3 client", "error", err)
return err
}
ensureCtx, cancelEnsure := context.WithTimeout(context.Background(), 10*time.Second)
err = s3Client.EnsureBucket(ensureCtx)
cancelEnsure()
if err != nil {
log.Error("ensure s3 bucket", "error", err)
return err
}
log.Info("s3 storage ready", "endpoint", cfg.S3.Endpoint, "bucket", s3Client.Bucket())
brokerURL, err := cfg.Broker.URL()
if err != nil {
log.Error("read broker url", "error", err)
return err
}
publisher := outbox.NewPublisher(pool, brokerURL, log)
backgroundCtx, stopBackground := context.WithCancel(context.Background())
var backgroundWG sync.WaitGroup
backgroundWG.Go(func() {
publisher.Run(backgroundCtx)
})
backgroundWG.Go(func() {
runSessionCleanup(backgroundCtx, log, queries, sessionCleanupInterval)
})
backgroundWG.Go(func() {
runIdempotencyCleanup(backgroundCtx, log, queries, cfg.Server.IdempotencyTTL, idempotencyCleanupInterval)
})
defer func() {
stopBackground()
backgroundWG.Wait()
}()
authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log)
userService := service.NewUserService(queries)
chatService := service.NewChatService(pool, queries)
messageService := service.NewMessageService(pool, queries)
attachmentService := service.NewAttachmentService(pool, queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels)
router := NewRouter(
log,
cfg.Server.InstanceID,
cfg.Server.MaxInflightRequests,
cfg.S3.MaxUploadBytes,
rdb,
pool,
s3Client,
authService,
userService,
chatService,
messageService,
attachmentService,
)
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)
if tlslisten.TLSEnabled() {
tlsCfg, terr := tlslisten.LoadServerTLS(
cfg.Server.TLSCertFile,
cfg.Server.TLSKeyFile,
cfg.Server.TLSCAFile,
cfg.Server.TLSClientSAN,
)
if terr != nil {
serverErrors <- terr
return
}
serverErrors <- tlslisten.ListenAndServeTLS(server, tlsCfg)
return
}
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
}
}
+72
View File
@@ -0,0 +1,72 @@
package app
import (
"context"
"log/slog"
"time"
)
const (
sessionCleanupInterval = time.Hour
idempotencyCleanupInterval = time.Hour
)
type sessionCleaner interface {
DeleteExpiredSessions(ctx context.Context) (int64, error)
}
type idempotencyCleaner interface {
DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error)
}
func runSessionCleanup(ctx context.Context, log *slog.Logger, q sessionCleaner, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
n, err := q.DeleteExpiredSessions(ctx)
if err != nil {
if ctx.Err() == nil {
log.Error("delete expired sessions", "error", err)
}
continue
}
if n > 0 {
log.Info("expired sessions deleted", "count", n)
}
}
}
}
func runIdempotencyCleanup(
ctx context.Context,
log *slog.Logger,
q idempotencyCleaner,
ttl time.Duration,
interval time.Duration,
) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
n, err := q.DeleteExpiredIdempotencyKeys(ctx, time.Now().Add(-ttl))
if err != nil {
if ctx.Err() == nil {
log.Error("delete expired idempotency keys", "error", err)
}
continue
}
if n > 0 {
log.Info("expired idempotency keys deleted", "count", n)
}
}
}
}
+65
View File
@@ -0,0 +1,65 @@
package app
import (
"context"
"fmt"
"net/http"
"os"
"time"
"gavrilenko-sxdees/lab7/internal/config"
"gavrilenko-sxdees/lab7/internal/tlslisten"
"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()
scheme := "http"
if tlslisten.TLSEnabled() {
scheme = "https"
}
url := fmt.Sprintf("%s://localhost:%s/health/ready", scheme, 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
}
client := http.DefaultClient
if tlslisten.TLSEnabled() {
hc, herr := tlslisten.ClientHTTP(
os.Getenv("TLS_HEALTH_CLIENT_CERT"),
os.Getenv("TLS_HEALTH_CLIENT_KEY"),
cfg.Server.TLSCAFile,
)
if herr != nil {
fmt.Fprintln(os.Stderr, "healthcheck: tls client:", herr)
return 1
}
client = hc
}
resp, err := client.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
}
+77
View File
@@ -0,0 +1,77 @@
package app
import (
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
goredis "github.com/redis/go-redis/v9"
"gavrilenko-sxdees/lab7/internal/handler"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/internal/service"
)
func NewRouter(
log *slog.Logger,
instanceID string,
maxInflightRequests int,
maxUploadBytes int,
sessionCache *goredis.Client,
db handler.Pinger,
storage handler.Pinger,
authService *service.AuthService,
userService *service.UserService,
chatService *service.ChatService,
messageService *service.MessageService,
attachmentService *service.AttachmentService,
) http.Handler {
router := chi.NewRouter()
loginLimiter := middleware.NewLoginLimiter(sessionCache)
healthHandler := handler.NewHealthHandler(log, db, storage)
authHandler := handler.NewAuthHandler(authService)
userHandler := handler.NewUserHandler(userService)
chatHandler := handler.NewChatHandler(chatService)
messageHandler := handler.NewMessageHandler(messageService)
attachmentHandler := handler.NewAttachmentHandler(attachmentService, maxUploadBytes)
router.Use(middleware.InstanceID(instanceID))
router.Use(middleware.Telemetry())
router.Use(middleware.RequestTimeout(5 * time.Second))
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.With(loginLimiter.Limit).Post("/api/v1/auth/sessions", authHandler.CreateSession)
router.Delete("/api/v1/auth/sessions/current", authHandler.RevokeSession)
router.Group(func(r chi.Router) {
r.Use(middleware.Auth(authService))
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)
r.Post("/api/v1/chats/{chat_id}/attachments", attachmentHandler.Upload)
r.Get("/api/v1/attachments/{attachment_id}", attachmentHandler.Get)
r.Get("/api/v1/attachments/{attachment_id}/content", attachmentHandler.GetContent)
})
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
}
+267
View File
@@ -0,0 +1,267 @@
package config
import (
"fmt"
"log"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
SessionStorePostgres = "postgres"
SessionStoreRedis = "redis"
)
type Config struct {
Server ServerConfig
Logging LoggingConfig
Database DatabaseConfig
Redis RedisConfig
Broker BrokerConfig
S3 S3Config
SessionStore string
}
func (c Config) UseCache() bool {
return c.SessionStore == SessionStoreRedis
}
type ServerConfig struct {
Host string
Port string
MaxInflightRequests int
SessionTTL time.Duration
IdempotencyTTL time.Duration
InstanceID string
TLSCertFile string
TLSKeyFile string
TLSCAFile string
TLSClientSAN string
}
type LoggingConfig struct {
Level slog.Level
}
type DatabaseConfig struct {
URLFile string
}
func (c DatabaseConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
type RedisConfig struct {
URLFile string
}
func (c RedisConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
type BrokerConfig struct {
URLFile string
}
func (c BrokerConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
type S3Config struct {
Endpoint string
Region string
Bucket string
APIAccessKeyFile string
APISecretKeyFile string
BootstrapAccessKeyFile string
BootstrapSecretKeyFile string
MaxUploadBytes int
MaxImagePixels int
StagingRetention time.Duration
}
func (c S3Config) APIAccessKey() (string, error) {
return readSecretFile(c.APIAccessKeyFile)
}
func (c S3Config) APISecretKey() (string, error) {
return readSecretFile(c.APISecretKeyFile)
}
func (c S3Config) BootstrapAccessKey() (string, error) {
return readSecretFile(c.BootstrapAccessKeyFile)
}
func (c S3Config) BootstrapSecretKey() (string, error) {
return readSecretFile(c.BootstrapSecretKeyFile)
}
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,
IdempotencyTTL: time.Duration(getEnvPositiveInt("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second,
InstanceID: getInstanceID("INSTANCE_ID"),
TLSCertFile: getEnv("TLS_CERT_FILE", ""),
TLSKeyFile: getEnv("TLS_KEY_FILE", ""),
TLSCAFile: getEnv("TLS_CA_FILE", ""),
TLSClientSAN: getEnv("TLS_CLIENT_SAN", "lb.messenger.lab"),
},
Logging: LoggingConfig{
Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo),
},
Database: DatabaseConfig{
URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"),
},
Redis: RedisConfig{
URLFile: getEnv("CACHE_URL_FILE", "/run/secrets/cache_url"),
},
Broker: BrokerConfig{
URLFile: getEnv("BROKER_URL_FILE", "/run/secrets/broker_url"),
},
S3: LoadS3(),
SessionStore: getEnvSessionStore("SESSION_STORE", SessionStorePostgres),
}
}
func LoadS3() S3Config {
return S3Config{
Endpoint: getEnv("S3_ENDPOINT", "http://s3:9000"),
Region: getEnv("S3_REGION", "us-east-1"),
Bucket: getEnv("S3_BUCKET", "messenger-attachments"),
APIAccessKeyFile: getEnv("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id"),
APISecretKeyFile: getEnv("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key"),
BootstrapAccessKeyFile: getEnv("S3_BOOTSTRAP_ACCESS_KEY_ID_FILE", "/run/secrets/s3_bootstrap_access_key_id"),
BootstrapSecretKeyFile: getEnv("S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_bootstrap_secret_access_key"),
MaxUploadBytes: getEnvPositiveInt("MAX_UPLOAD_BYTES", 10485760),
MaxImagePixels: getEnvPositiveInt("MAX_IMAGE_PIXELS", 40000000),
StagingRetention: time.Duration(getEnvPositiveInt("STAGING_RETENTION_SECONDS", 86400)) * time.Second,
}
}
type WorkerConfig struct {
Concurrency int
MaxAttempts int
Timeout time.Duration
}
func LoadWorker() WorkerConfig {
return WorkerConfig{
Concurrency: getEnvPositiveInt("WORKER_CONCURRENCY", 2),
MaxAttempts: getEnvPositiveInt("JOB_MAX_ATTEMPTS", 5),
Timeout: time.Duration(getEnvPositiveInt("JOB_TIMEOUT_SECONDS", 60)) * time.Second,
}
}
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
}
func getEnvSessionStore(key, def string) string {
v := strings.ToLower(os.Getenv(key))
switch v {
case "":
return def
case SessionStorePostgres, SessionStoreRedis:
return v
default:
log.Printf("invalid session store for %s=%q, using default %s", key, v, def)
return def
}
}
func getInstanceID(key string) string {
if v := os.Getenv(key); v != "" {
return v
}
host, err := os.Hostname()
if err != nil || host == "" {
log.Printf("cannot determine hostname, using \"unknown\" for %s: %v", key, err)
return "unknown"
}
return host
}
+157
View File
@@ -0,0 +1,157 @@
package credentials
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"os"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
)
const tokenSize = 32
var (
ErrPasswordMismatch = errors.New("password mismatch")
defaultMemoryKiB = 19456
defaultIterations = 2
defaultParallelism = 1
defaultSaltLen = 16
defaultKeyLen = 32
)
func init() {
if v := os.Getenv("ARGON2_MEMORY_KIB"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
defaultMemoryKiB = n
}
}
if v := os.Getenv("ARGON2_ITERATIONS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
defaultIterations = n
}
}
if v := os.Getenv("ARGON2_PARALLELISM"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
defaultParallelism = n
}
}
}
var dummyHash, _ = HashPassword("dummy-password-for-timing")
func DummyVerify(plain string) {
_ = VerifyPassword(dummyHash, plain)
}
func HashPassword(plain string) (string, error) {
salt := make([]byte, defaultSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(plain), salt, uint32(defaultIterations), uint32(defaultMemoryKiB), uint8(defaultParallelism), uint32(defaultKeyLen))
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
defaultMemoryKiB, defaultIterations, defaultParallelism, b64Salt, b64Hash), nil
}
func VerifyPassword(encoded, plain string) error {
if strings.HasPrefix(encoded, "$argon2id$") {
return verifyArgon2id(encoded, plain)
}
err := bcrypt.CompareHashAndPassword([]byte(encoded), prehashBcrypt(plain))
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return ErrPasswordMismatch
}
return err
}
func NeedsRehash(encoded string) bool {
if !strings.HasPrefix(encoded, "$argon2id$") {
return true
}
mem, iter, par, ok := parseArgon2Params(encoded)
if !ok {
return true
}
return mem != defaultMemoryKiB || iter != defaultIterations || par != defaultParallelism
}
func verifyArgon2id(encoded, plain string) error {
mem, iter, par, ok := parseArgon2Params(encoded)
if !ok {
return fmt.Errorf("invalid argon2 hash")
}
parts := strings.Split(encoded, "$")
if len(parts) != 6 {
return fmt.Errorf("invalid argon2 hash")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return err
}
want, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return err
}
got := argon2.IDKey([]byte(plain), salt, uint32(iter), uint32(mem), uint8(par), uint32(len(want)))
if subtle.ConstantTimeCompare(got, want) != 1 {
return ErrPasswordMismatch
}
return nil
}
func parseArgon2Params(encoded string) (memory, iterations, parallelism int, ok bool) {
idx := strings.Index(encoded, "$m=")
if idx < 0 {
return 0, 0, 0, false
}
rest := encoded[idx+1:]
fields := strings.Split(rest, "$")
if len(fields) < 1 {
return 0, 0, 0, false
}
for _, part := range strings.Split(fields[0], ",") {
kv := strings.SplitN(part, "=", 2)
if len(kv) != 2 {
continue
}
n, err := strconv.Atoi(kv[1])
if err != nil {
return 0, 0, 0, false
}
switch kv[0] {
case "m":
memory = n
case "t":
iterations = n
case "p":
parallelism = n
}
}
return memory, iterations, parallelism, memory > 0 && iterations > 0 && parallelism > 0
}
func prehashBcrypt(plain string) []byte {
sum := sha256.Sum256([]byte(plain))
return []byte(base64.StdEncoding.EncodeToString(sum[:]))
}
func NewToken() string {
raw := make([]byte, tokenSize)
_, _ = rand.Read(raw)
return base64.RawURLEncoding.EncodeToString(raw)
}
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
+47
View File
@@ -0,0 +1,47 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: attachment_replays.sql
package db
import (
"context"
"github.com/google/uuid"
)
const createAttachmentReplay = `-- name: CreateAttachmentReplay :exec
INSERT INTO attachment_replays (
attachment_id,
attempt,
previous_error_code,
operator,
reason
) VALUES (
$1,
$2,
$3,
$4,
$5
)
`
type CreateAttachmentReplayParams struct {
AttachmentID uuid.UUID
Attempt int
PreviousErrorCode *string
Operator string
Reason string
}
func (q *Queries) CreateAttachmentReplay(ctx context.Context, arg CreateAttachmentReplayParams) error {
_, err := q.db.Exec(ctx, createAttachmentReplay,
arg.AttachmentID,
arg.Attempt,
arg.PreviousErrorCode,
arg.Operator,
arg.Reason,
)
return err
}
+105
View File
@@ -0,0 +1,105 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: attachment_variants.sql
package db
import (
"context"
"github.com/google/uuid"
)
const createAttachmentVariant = `-- name: CreateAttachmentVariant :exec
INSERT INTO attachment_variants (
attachment_id,
pipeline_version,
variant,
s3_key,
content_type,
size_bytes,
width,
height,
sha256
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9
)
`
type CreateAttachmentVariantParams struct {
AttachmentID uuid.UUID
PipelineVersion int
Variant AttachmentVariantName
S3Key string
ContentType string
SizeBytes int
Width int
Height int
Sha256 string
}
func (q *Queries) CreateAttachmentVariant(ctx context.Context, arg CreateAttachmentVariantParams) error {
_, err := q.db.Exec(ctx, createAttachmentVariant,
arg.AttachmentID,
arg.PipelineVersion,
arg.Variant,
arg.S3Key,
arg.ContentType,
arg.SizeBytes,
arg.Width,
arg.Height,
arg.Sha256,
)
return err
}
const listAttachmentVariants = `-- name: ListAttachmentVariants :many
SELECT attachment_id, pipeline_version, variant, s3_key, content_type, size_bytes, sha256, width, height FROM attachment_variants
WHERE attachment_id = $1::uuid
AND pipeline_version = $2::int
ORDER BY variant
`
type ListAttachmentVariantsParams struct {
AttachmentID uuid.UUID
PipelineVersion int
}
func (q *Queries) ListAttachmentVariants(ctx context.Context, arg ListAttachmentVariantsParams) ([]AttachmentVariant, error) {
rows, err := q.db.Query(ctx, listAttachmentVariants, arg.AttachmentID, arg.PipelineVersion)
if err != nil {
return nil, err
}
defer rows.Close()
items := []AttachmentVariant{}
for rows.Next() {
var i AttachmentVariant
if err := rows.Scan(
&i.AttachmentID,
&i.PipelineVersion,
&i.Variant,
&i.S3Key,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Width,
&i.Height,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+799
View File
@@ -0,0 +1,799 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: attachments.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const claimAttachmentJob = `-- name: ClaimAttachmentJob :one
UPDATE attachments
SET status = 'processing',
attempts = attempts + 1,
lease_until = $1::timestamptz,
updated_at = now()
WHERE id = $2::uuid
AND job_id = $3::uuid
AND pipeline_version = $4::int
AND status = 'queued'
AND attempts + 1 = $5::int
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until
`
type ClaimAttachmentJobParams struct {
LeaseUntil time.Time
ID uuid.UUID
JobID uuid.UUID
PipelineVersion int
Attempt int
}
func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJobParams) (Attachment, error) {
row := q.db.QueryRow(ctx, claimAttachmentJob,
arg.LeaseUntil,
arg.ID,
arg.JobID,
arg.PipelineVersion,
arg.Attempt,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const clearAttachmentStagingKey = `-- name: ClearAttachmentStagingKey :exec
UPDATE attachments
SET staging_key = NULL
WHERE id = $1::uuid
`
func (q *Queries) ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, clearAttachmentStagingKey, id)
return err
}
const completeAttachmentJob = `-- name: CompleteAttachmentJob :execrows
UPDATE attachments
SET status = 'ready',
error_code = NULL,
lease_until = NULL,
updated_at = now()
WHERE id = $1::uuid
AND status = 'processing'
AND attempts = $2::int
AND lease_until > now()
`
type CompleteAttachmentJobParams struct {
ID uuid.UUID
Attempt int
}
func (q *Queries) CompleteAttachmentJob(ctx context.Context, arg CompleteAttachmentJobParams) (int64, error) {
result, err := q.db.Exec(ctx, completeAttachmentJob, arg.ID, arg.Attempt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const createAttachment = `-- name: CreateAttachment :one
INSERT INTO attachments (
id,
chat_id,
owner_id,
s3_key,
staging_key,
job_id,
filename,
content_type,
size_bytes,
sha256,
width,
height,
error_code
)
SELECT
$1::uuid,
$2::uuid,
$3::uuid,
$4::text,
$5::text,
$6::uuid,
$7::text,
$8::attachment_content_type,
$9::int,
$10::text,
$11::int,
$12::int,
NULLIF($13::text, '')
WHERE EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = $2
AND user_id = $3
)
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until
`
type CreateAttachmentParams struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
S3Key string
StagingKey string
JobID uuid.UUID
Filename string
ContentType AttachmentContentType
SizeBytes int
Sha256 string
Width int
Height int
ErrorCode string
}
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, createAttachment,
arg.ID,
arg.ChatID,
arg.OwnerID,
arg.S3Key,
arg.StagingKey,
arg.JobID,
arg.Filename,
arg.ContentType,
arg.SizeBytes,
arg.Sha256,
arg.Width,
arg.Height,
arg.ErrorCode,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const createMessageAttachment = `-- name: CreateMessageAttachment :exec
INSERT INTO message_attachments (
message_id,
attachment_id,
position
) VALUES (
$1,
$2,
$3
)
`
type CreateMessageAttachmentParams struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Position int
}
func (q *Queries) CreateMessageAttachment(ctx context.Context, arg CreateMessageAttachmentParams) error {
_, err := q.db.Exec(ctx, createMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Position)
return err
}
const failAttachmentJob = `-- name: FailAttachmentJob :execrows
UPDATE attachments
SET status = 'failed',
error_code = $1::text,
lease_until = NULL,
updated_at = now()
WHERE id = $2::uuid
AND status = 'processing'
AND attempts = $3::int
AND lease_until > now()
`
type FailAttachmentJobParams struct {
ErrorCode string
ID uuid.UUID
Attempt int
}
func (q *Queries) FailAttachmentJob(ctx context.Context, arg FailAttachmentJobParams) (int64, error) {
result, err := q.db.Exec(ctx, failAttachmentJob, arg.ErrorCode, arg.ID, arg.Attempt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const failExpiredAttachmentJob = `-- name: FailExpiredAttachmentJob :execrows
UPDATE attachments
SET status = 'failed',
error_code = 'retry_exhausted',
lease_until = NULL,
updated_at = now()
WHERE id = $1::uuid
AND status = 'processing'
AND lease_until <= now()
`
func (q *Queries) FailExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, failExpiredAttachmentJob, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getAttachmentByID = `-- name: GetAttachmentByID :one
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE id = $1::uuid
`
func (q *Queries) GetAttachmentByID(ctx context.Context, dollar_1 uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachmentByID, dollar_1)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const listAttachmentsByIDs = `-- name: ListAttachmentsByIDs :many
SELECT status
FROM attachments
WHERE chat_id = $1::uuid
AND id = ANY($2::uuid[])
`
type ListAttachmentsByIDsParams struct {
ChatID uuid.UUID
Ids []uuid.UUID
}
func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsByIDsParams) ([]AttachmentStatus, error) {
rows, err := q.db.Query(ctx, listAttachmentsByIDs, arg.ChatID, arg.Ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []AttachmentStatus{}
for rows.Next() {
var status AttachmentStatus
if err := rows.Scan(&status); err != nil {
return nil, err
}
items = append(items, status)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAttachmentsForReconcile = `-- name: ListAttachmentsForReconcile :many
SELECT id, s3_key, staging_key, status, size_bytes, updated_at
FROM attachments
`
type ListAttachmentsForReconcileRow struct {
ID uuid.UUID
S3Key string
StagingKey *string
Status AttachmentStatus
SizeBytes int
UpdatedAt time.Time
}
func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttachmentsForReconcileRow, error) {
rows, err := q.db.Query(ctx, listAttachmentsForReconcile)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListAttachmentsForReconcileRow{}
for rows.Next() {
var i ListAttachmentsForReconcileRow
if err := rows.Scan(
&i.ID,
&i.S3Key,
&i.StagingKey,
&i.Status,
&i.SizeBytes,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listFailedAttachments = `-- name: ListFailedAttachments :many
SELECT id, job_id, error_code, attempts, updated_at
FROM attachments
WHERE status = 'failed'
ORDER BY updated_at, id
LIMIT $1::int
`
type ListFailedAttachmentsRow struct {
ID uuid.UUID
JobID *uuid.UUID
ErrorCode *string
Attempts int
UpdatedAt time.Time
}
func (q *Queries) ListFailedAttachments(ctx context.Context, batchSize int) ([]ListFailedAttachmentsRow, error) {
rows, err := q.db.Query(ctx, listFailedAttachments, batchSize)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListFailedAttachmentsRow{}
for rows.Next() {
var i ListFailedAttachmentsRow
if err := rows.Scan(
&i.ID,
&i.JobID,
&i.ErrorCode,
&i.Attempts,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many
SELECT attachment_id
FROM message_attachments
WHERE message_id = $1::uuid
ORDER BY position
`
func (q *Queries) ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, listMessageAttachmentIDs, messageID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var attachment_id uuid.UUID
if err := rows.Scan(&attachment_id); err != nil {
return nil, err
}
items = append(items, attachment_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessageAttachmentsByMessageIDs = `-- name: ListMessageAttachmentsByMessageIDs :many
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY($1::uuid[])
ORDER BY message_id, position
`
type ListMessageAttachmentsByMessageIDsRow struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
}
func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsByMessageIDsRow, error) {
rows, err := q.db.Query(ctx, listMessageAttachmentsByMessageIDs, messageIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListMessageAttachmentsByMessageIDsRow{}
for rows.Next() {
var i ListMessageAttachmentsByMessageIDsRow
if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockAttachmentByStagingKey = `-- name: LockAttachmentByStagingKey :one
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE staging_key = $1::text
FOR UPDATE
`
func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (Attachment, error) {
row := q.db.QueryRow(ctx, lockAttachmentByStagingKey, stagingKey)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const lockAttachmentForUpgrade = `-- name: LockAttachmentForUpgrade :one
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE id = $1::uuid
AND pipeline_version = 1
AND status IN ('queued', 'processing')
AND staging_key IS NOT NULL
FOR UPDATE
`
func (q *Queries) LockAttachmentForUpgrade(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, lockAttachmentForUpgrade, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const lockAttachmentJob = `-- name: LockAttachmentJob :one
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE id = $1::uuid
AND status = 'processing'
AND job_id = $2::uuid
AND pipeline_version = $3::int
AND attempts = $4::int
AND lease_until > now()
FOR UPDATE
`
type LockAttachmentJobParams struct {
ID uuid.UUID
JobID uuid.UUID
PipelineVersion int
Attempt int
}
func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobParams) (Attachment, error) {
row := q.db.QueryRow(ctx, lockAttachmentJob,
arg.ID,
arg.JobID,
arg.PipelineVersion,
arg.Attempt,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const lockExpiredAttachmentJobs = `-- name: LockExpiredAttachmentJobs :many
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE status = 'processing'
AND lease_until <= now()
ORDER BY lease_until, id
LIMIT $1::int
FOR UPDATE SKIP LOCKED
`
func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int) ([]Attachment, error) {
rows, err := q.db.Query(ctx, lockExpiredAttachmentJobs, batchSize)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
for rows.Next() {
var i Attachment
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockFailedAttachmentForReplay = `-- name: LockFailedAttachmentForReplay :one
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
WHERE id = $1::uuid
AND status = 'failed'
AND staging_key IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM attachment_variants
WHERE attachment_id = attachments.id
)
FOR UPDATE
`
func (q *Queries) LockFailedAttachmentForReplay(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, lockFailedAttachmentForReplay, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.S3Key,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.ErrorCode,
&i.CreatedAt,
&i.UpdatedAt,
&i.StagingKey,
&i.JobID,
&i.PipelineVersion,
&i.Attempts,
&i.RetryBase,
&i.Width,
&i.Height,
&i.LeaseUntil,
)
return i, err
}
const markAttachmentFailedIfReady = `-- name: MarkAttachmentFailedIfReady :execrows
UPDATE attachments
SET status = 'failed',
error_code = $1::text,
updated_at = now()
WHERE id = $2::uuid AND status = 'ready'
`
type MarkAttachmentFailedIfReadyParams struct {
ErrorCode string
ID uuid.UUID
}
func (q *Queries) MarkAttachmentFailedIfReady(ctx context.Context, arg MarkAttachmentFailedIfReadyParams) (int64, error) {
result, err := q.db.Exec(ctx, markAttachmentFailedIfReady, arg.ErrorCode, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const recoverExpiredAttachmentJob = `-- name: RecoverExpiredAttachmentJob :execrows
UPDATE attachments
SET status = 'queued',
lease_until = NULL,
updated_at = now()
WHERE id = $1::uuid
AND status = 'processing'
AND lease_until <= now()
`
func (q *Queries) RecoverExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, recoverExpiredAttachmentJob, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const replayAttachmentJob = `-- name: ReplayAttachmentJob :execrows
UPDATE attachments
SET status = 'queued',
retry_base = attempts,
error_code = NULL,
lease_until = NULL,
updated_at = now()
WHERE id = $1::uuid
AND status = 'failed'
AND staging_key IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM attachment_variants
WHERE attachment_id = attachments.id
)
`
func (q *Queries) ReplayAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, replayAttachmentJob, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const retryAttachmentJob = `-- name: RetryAttachmentJob :execrows
UPDATE attachments
SET status = 'queued',
error_code = $1::text,
lease_until = NULL,
updated_at = now()
WHERE id = $2::uuid
AND status = 'processing'
AND attempts = $3::int
AND lease_until > now()
`
type RetryAttachmentJobParams struct {
ErrorCode string
ID uuid.UUID
Attempt int
}
func (q *Queries) RetryAttachmentJob(ctx context.Context, arg RetryAttachmentJobParams) (int64, error) {
result, err := q.db.Exec(ctx, retryAttachmentJob, arg.ErrorCode, arg.ID, arg.Attempt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const upgradeAttachmentPipeline = `-- name: UpgradeAttachmentPipeline :execrows
UPDATE attachments
SET pipeline_version = 2,
status = 'queued',
retry_base = attempts,
error_code = NULL,
lease_until = NULL,
updated_at = now()
WHERE id = $1::uuid
AND pipeline_version = 1
AND status IN ('queued', 'processing')
AND staging_key IS NOT NULL
`
func (q *Queries) UpgradeAttachmentPipeline(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, upgradeAttachmentPipeline, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+232
View File
@@ -0,0 +1,232 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// 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 listChatsAfter = `-- name: ListChatsAfter :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 (c.created_at, c.id) > (
$2::timestamptz,
$3::uuid
)
ORDER BY c.created_at, c.id
LIMIT $4
`
type ListChatsAfterParams struct {
UserID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
Lim int
}
type ListChatsAfterRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) {
rows, err := q.db.Query(ctx, listChatsAfter,
arg.UserID,
arg.AfterCreatedAt,
arg.AfterID,
arg.Lim,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsAfterRow{}
for rows.Next() {
var i ListChatsAfterRow
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
}
const listChatsFirstPage = `-- name: ListChatsFirstPage :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
ORDER BY c.created_at, c.id
LIMIT $2
`
type ListChatsFirstPageParams struct {
UserID uuid.UUID
Lim int
}
type ListChatsFirstPageRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) {
rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsFirstPageRow{}
for rows.Next() {
var i ListChatsFirstPageRow
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.29.0
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,
}
}
+120
View File
@@ -0,0 +1,120 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: idempotency_keys.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const createIdempotencyKey = `-- name: CreateIdempotencyKey :execrows
INSERT INTO idempotency_keys (
user_id,
method,
path,
key,
request_hash,
message_id
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
ON CONFLICT DO NOTHING
`
type CreateIdempotencyKeyParams struct {
UserID uuid.UUID
Method string
Path string
Key string
RequestHash string
MessageID uuid.UUID
}
func (q *Queries) CreateIdempotencyKey(ctx context.Context, arg CreateIdempotencyKeyParams) (int64, error) {
result, err := q.db.Exec(ctx, createIdempotencyKey,
arg.UserID,
arg.Method,
arg.Path,
arg.Key,
arg.RequestHash,
arg.MessageID,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteExpiredIdempotencyKeys = `-- name: DeleteExpiredIdempotencyKeys :execrows
DELETE FROM idempotency_keys
WHERE created_at < $1
`
func (q *Queries) DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredIdempotencyKeys, cutoff)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getIdempotentMessage = `-- name: GetIdempotentMessage :one
SELECT
k.request_hash,
m.id,
m.chat_id,
m.sender_id,
m.text,
m.created_at
FROM idempotency_keys AS k
JOIN messages AS m ON m.id = k.message_id
WHERE k.user_id = $1
AND k.method = $2
AND k.path = $3
AND k.key = $4
`
type GetIdempotentMessageParams struct {
UserID uuid.UUID
Method string
Path string
Key string
}
type GetIdempotentMessageRow struct {
RequestHash string
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
func (q *Queries) GetIdempotentMessage(ctx context.Context, arg GetIdempotentMessageParams) (GetIdempotentMessageRow, error) {
row := q.db.QueryRow(ctx, getIdempotentMessage,
arg.UserID,
arg.Method,
arg.Path,
arg.Key,
)
var i GetIdempotentMessageRow
err := row.Scan(
&i.RequestHash,
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
+145
View File
@@ -0,0 +1,145 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// 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 listMessagesAfter = `-- name: ListMessagesAfter :many
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
AND (created_at, id) > (
$2::timestamptz,
$3::uuid
)
ORDER BY created_at, id
LIMIT $4
`
type ListMessagesAfterParams struct {
ChatID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
Lim int
}
func (q *Queries) ListMessagesAfter(ctx context.Context, arg ListMessagesAfterParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesAfter,
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
}
const listMessagesFirstPage = `-- name: ListMessagesFirstPage :many
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
`
type ListMessagesFirstPageParams struct {
ChatID uuid.UUID
Lim int
}
func (q *Queries) ListMessagesFirstPage(ctx context.Context, arg ListMessagesFirstPageParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesFirstPage, arg.ChatID, 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
}
+249
View File
@@ -0,0 +1,249 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
package db
import (
"database/sql/driver"
"fmt"
"time"
"github.com/google/uuid"
)
type AttachmentContentType string
const (
AttachmentContentTypeImagePng AttachmentContentType = "image/png"
AttachmentContentTypeImageJpeg AttachmentContentType = "image/jpeg"
)
func (e *AttachmentContentType) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
*e = AttachmentContentType(s)
case string:
*e = AttachmentContentType(s)
default:
return fmt.Errorf("unsupported scan type for AttachmentContentType: %T", src)
}
return nil
}
type NullAttachmentContentType struct {
AttachmentContentType AttachmentContentType
Valid bool // Valid is true if AttachmentContentType is not NULL
}
// Scan implements the Scanner interface.
func (ns *NullAttachmentContentType) Scan(value interface{}) error {
if value == nil {
ns.AttachmentContentType, ns.Valid = "", false
return nil
}
ns.Valid = true
return ns.AttachmentContentType.Scan(value)
}
// Value implements the driver Valuer interface.
func (ns NullAttachmentContentType) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return string(ns.AttachmentContentType), nil
}
type AttachmentStatus string
const (
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
)
func (e *AttachmentStatus) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
*e = AttachmentStatus(s)
case string:
*e = AttachmentStatus(s)
default:
return fmt.Errorf("unsupported scan type for AttachmentStatus: %T", src)
}
return nil
}
type NullAttachmentStatus struct {
AttachmentStatus AttachmentStatus
Valid bool // Valid is true if AttachmentStatus is not NULL
}
// Scan implements the Scanner interface.
func (ns *NullAttachmentStatus) Scan(value interface{}) error {
if value == nil {
ns.AttachmentStatus, ns.Valid = "", false
return nil
}
ns.Valid = true
return ns.AttachmentStatus.Scan(value)
}
// Value implements the driver Valuer interface.
func (ns NullAttachmentStatus) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return string(ns.AttachmentStatus), nil
}
type AttachmentVariantName string
const (
AttachmentVariantNameThumbnail AttachmentVariantName = "thumbnail"
AttachmentVariantNameCrop AttachmentVariantName = "crop"
AttachmentVariantNameOptimized AttachmentVariantName = "optimized"
)
func (e *AttachmentVariantName) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
*e = AttachmentVariantName(s)
case string:
*e = AttachmentVariantName(s)
default:
return fmt.Errorf("unsupported scan type for AttachmentVariantName: %T", src)
}
return nil
}
type NullAttachmentVariantName struct {
AttachmentVariantName AttachmentVariantName
Valid bool // Valid is true if AttachmentVariantName is not NULL
}
// Scan implements the Scanner interface.
func (ns *NullAttachmentVariantName) Scan(value interface{}) error {
if value == nil {
ns.AttachmentVariantName, ns.Valid = "", false
return nil
}
ns.Valid = true
return ns.AttachmentVariantName.Scan(value)
}
// Value implements the driver Valuer interface.
func (ns NullAttachmentVariantName) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return string(ns.AttachmentVariantName), nil
}
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
S3Key string
Filename string
ContentType AttachmentContentType
SizeBytes int
Sha256 string
Status AttachmentStatus
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
StagingKey *string
JobID *uuid.UUID
PipelineVersion int
Attempts int
RetryBase int
Width *int32
Height *int32
LeaseUntil *time.Time
}
type AttachmentReplay struct {
AttachmentID uuid.UUID
Attempt int
PreviousErrorCode *string
Operator string
Reason string
CreatedAt time.Time
}
type AttachmentVariant struct {
AttachmentID uuid.UUID
PipelineVersion int
Variant AttachmentVariantName
S3Key string
ContentType string
SizeBytes int
Sha256 string
Width int
Height int
}
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
}
type IdempotencyKey struct {
UserID uuid.UUID
Method string
Path string
Key string
RequestHash string
MessageID uuid.UUID
CreatedAt time.Time
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type MessageAttachment struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Position int
}
type Outbox struct {
ID int64
JobID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int
Attempt int
CreatedAt time.Time
AvailableAt time.Time
PublishedAt *time.Time
Traceparent string
Tracestate string
}
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
}
+124
View File
@@ -0,0 +1,124 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: outbox.sql
package db
import (
"context"
"time"
"github.com/google/uuid"
)
const createOutboxEntry = `-- name: CreateOutboxEntry :one
INSERT INTO outbox (
job_id,
attachment_id,
pipeline_version,
attempt,
available_at,
traceparent,
tracestate
)
SELECT
job_id,
id,
pipeline_version,
$1::int,
$2::timestamptz,
$3::text,
$4::text
FROM attachments
WHERE id = $5::uuid
AND job_id IS NOT NULL
RETURNING id, job_id, attachment_id, pipeline_version, attempt, created_at, available_at, published_at, traceparent, tracestate
`
type CreateOutboxEntryParams struct {
Attempt int
AvailableAt time.Time
Traceparent string
Tracestate string
AttachmentID uuid.UUID
}
func (q *Queries) CreateOutboxEntry(ctx context.Context, arg CreateOutboxEntryParams) (Outbox, error) {
row := q.db.QueryRow(ctx, createOutboxEntry,
arg.Attempt,
arg.AvailableAt,
arg.Traceparent,
arg.Tracestate,
arg.AttachmentID,
)
var i Outbox
err := row.Scan(
&i.ID,
&i.JobID,
&i.AttachmentID,
&i.PipelineVersion,
&i.Attempt,
&i.CreatedAt,
&i.AvailableAt,
&i.PublishedAt,
&i.Traceparent,
&i.Tracestate,
)
return i, err
}
const lockPendingOutboxEntries = `-- name: LockPendingOutboxEntries :many
SELECT id, job_id, attachment_id, pipeline_version, attempt, created_at, available_at, published_at, traceparent, tracestate FROM outbox
WHERE published_at IS NULL
AND available_at <= now()
ORDER BY available_at, id
LIMIT $1::int
FOR UPDATE SKIP LOCKED
`
func (q *Queries) LockPendingOutboxEntries(ctx context.Context, batchSize int) ([]Outbox, error) {
rows, err := q.db.Query(ctx, lockPendingOutboxEntries, batchSize)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Outbox{}
for rows.Next() {
var i Outbox
if err := rows.Scan(
&i.ID,
&i.JobID,
&i.AttachmentID,
&i.PipelineVersion,
&i.Attempt,
&i.CreatedAt,
&i.AvailableAt,
&i.PublishedAt,
&i.Traceparent,
&i.Tracestate,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markOutboxPublished = `-- name: MarkOutboxPublished :execrows
UPDATE outbox
SET published_at = now()
WHERE id = $1::bigint
AND published_at IS NULL
`
func (q *Queries) MarkOutboxPublished(ctx context.Context, id int64) (int64, error) {
result, err := q.db.Exec(ctx, markOutboxPublished, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+81
View File
@@ -0,0 +1,81 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// 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 :execrows
DELETE FROM sessions
WHERE token_hash = $1
AND expires_at > now()
`
func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, error) {
result, err := q.db.Exec(ctx, deleteSession, tokenHash)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getActiveSession = `-- name: GetActiveSession :one
SELECT user_id, expires_at FROM sessions
WHERE token_hash = $1
AND expires_at > now()
`
type GetActiveSessionRow struct {
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) GetActiveSession(ctx context.Context, tokenHash string) (GetActiveSessionRow, error) {
row := q.db.QueryRow(ctx, getActiveSession, tokenHash)
var i GetActiveSessionRow
err := row.Scan(&i.UserID, &i.ExpiresAt)
return i, err
}
+115
View File
@@ -0,0 +1,115 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// 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
}
const updatePasswordHash = `-- name: UpdatePasswordHash :exec
UPDATE users SET password_hash = $1 WHERE id = $2
`
type UpdatePasswordHashParams struct {
PasswordHash string
ID uuid.UUID
}
func (q *Queries) UpdatePasswordHash(ctx context.Context, arg UpdatePasswordHashParams) error {
_, err := q.db.Exec(ctx, updatePasswordHash, arg.PasswordHash, arg.ID)
return err
}
+98
View File
@@ -0,0 +1,98 @@
package dto
import (
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/model"
)
type CreateAttachmentRequest struct {
Filename string
}
type GetAttachmentContentRequest struct {
Variant string
}
type VariantResponse struct {
Name model.AttachmentVariantName `json:"name"`
ContentType model.ContentType `json:"content_type"`
SizeBytes int `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
Sha256 string `json:"sha256"`
}
type AttachmentResponse struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
OwnerID uuid.UUID `json:"owner_id"`
Filename string `json:"filename"`
ContentType model.ContentType `json:"content_type"`
SizeBytes int `json:"size_bytes"`
Sha256 string `json:"sha256"`
Status model.AttachmentStatus `json:"status"`
Variants []VariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (r CreateAttachmentRequest) Validate() bool {
if n := utf8.RuneCountInString(r.Filename); n < 1 || n > 255 {
return false
}
for _, ch := range r.Filename {
if ch == '/' || ch == '\\' || ch == 0 || unicode.IsControl(ch) {
return false
}
}
return true
}
func (r GetAttachmentContentRequest) Validate() bool {
switch model.AttachmentVariantName(r.Variant) {
case "",
model.AttachmentContentOriginal,
model.AttachmentVariantNameThumbnail,
model.AttachmentVariantNameCrop,
model.AttachmentVariantNameOptimized:
return true
default:
return false
}
}
func ToAttachmentResponse(a model.Attachment) AttachmentResponse {
variants := make([]VariantResponse, 0, len(a.Variants))
for _, v := range a.Variants {
variants = append(variants, VariantResponse{
Name: v.Name,
ContentType: v.ContentType,
SizeBytes: v.SizeBytes,
Width: v.Width,
Height: v.Height,
Sha256: v.Sha256,
})
}
return AttachmentResponse{
ID: a.ID,
ChatID: a.ChatID,
OwnerID: a.OwnerID,
Filename: a.Filename,
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
Sha256: a.Sha256,
Status: a.Status,
Variants: variants,
ErrorCode: a.ErrorCode,
CreatedAt: a.CreatedAt,
UpdatedAt: a.UpdatedAt,
}
}
+50
View File
@@ -0,0 +1,50 @@
package dto
import (
"gavrilenko-sxdees/lab7/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 {
if strings.TrimSpace(r.Title) == "" ||
strings.ContainsRune(r.Title, 0) ||
utf8.RuneCountInString(r.Title) > 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"`
}
+64
View File
@@ -0,0 +1,64 @@
package dto
import (
"gavrilenko-sxdees/lab7/internal/model"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type CreateMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessageResponse struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
SenderID uuid.UUID `json:"sender_id"`
Text string `json:"text"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
CreatedAt time.Time `json:"created_at"`
}
type MessagePageResponse struct {
Items []MessageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func (r CreateMessageRequest) Validate() bool {
if strings.ContainsRune(r.Text, 0) || utf8.RuneCountInString(r.Text) > 4000 {
return false
}
if len(r.AttachmentIDs) > 10 {
return false
}
seen := make(map[string]struct{}, len(r.AttachmentIDs))
for _, id := range r.AttachmentIDs {
if _, ok := seen[id]; ok {
return false
}
seen[id] = struct{}{}
}
hasText := strings.TrimSpace(r.Text) != ""
hasAttachment := len(r.AttachmentIDs) > 0
return hasText || hasAttachment
}
func ToMessageResponse(m model.Message) MessageResponse {
ids := make([]uuid.UUID, len(m.AttachmentIDs))
copy(ids, m.AttachmentIDs)
return MessageResponse{
ID: m.ID,
ChatID: m.ChatID,
SenderID: m.SenderID,
Text: m.Text,
AttachmentIDs: ids,
CreatedAt: m.CreatedAt,
}
}
+10
View File
@@ -0,0 +1,10 @@
package dto
import "time"
type SessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
User UserResponse `json:"user"`
}
+44
View File
@@ -0,0 +1,44 @@
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"`
Password string `json:"password"`
}
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 ||
strings.ContainsRune(r.DisplayName, 0) {
return false
}
if n := utf8.RuneCountInString(r.Password); n < 12 || n > 128 {
return false
}
return true
}
+140
View File
@@ -0,0 +1,140 @@
package handler
import (
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/internal/service"
)
type AttachmentHandler struct {
service *service.AttachmentService
maxBytes int
}
func NewAttachmentHandler(service *service.AttachmentService, maxBytes int) *AttachmentHandler {
return &AttachmentHandler{
service: service,
maxBytes: maxBytes,
}
}
func (h *AttachmentHandler) Upload(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
}
req := dto.CreateAttachmentRequest{
Filename: r.URL.Query().Get("filename"),
}
if !req.Validate() {
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid filename", requestID)
return
}
if deadline, ok := r.Context().Deadline(); ok {
controller := http.NewResponseController(w)
if err := controller.SetReadDeadline(deadline); err != nil {
httpx.WriteInternalError(w, requestID, err)
return
}
defer func() { _ = controller.SetReadDeadline(time.Time{}) }()
}
contentType := r.Header.Get("Content-Type")
r.Body = http.MaxBytesReader(w, r.Body, int64(h.maxBytes))
att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, r.Body, contentType)
switch {
case errors.Is(err, service.ErrUploadReadTimeout):
r.Close = true
w.Header().Set("Connection", "close")
httpx.WriteError(w, http.StatusRequestTimeout, dto.ErrorCodeInvalidRequest, "upload body read timed out", requestID)
return
case errors.Is(err, service.ErrInvalidSize):
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID)
return
case errors.Is(err, service.ErrInvalidImage):
httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "invalid image", requestID)
return
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
case err != nil:
httpx.WriteInternalError(w, requestID, err)
return
}
httpx.WriteJSON(w, http.StatusAccepted, dto.ToAttachmentResponse(att))
}
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
if err != nil {
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID)
return
}
att, err := h.service.Get(r.Context(), userID, attachmentID)
switch {
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
case err != nil:
httpx.WriteInternalError(w, requestID, err)
return
}
httpx.WriteJSON(w, http.StatusOK, dto.ToAttachmentResponse(att))
}
func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
userID := middleware.GetUserID(r.Context())
attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
if err != nil {
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID)
return
}
req := dto.GetAttachmentContentRequest{
Variant: r.URL.Query().Get("variant"),
}
if !req.Validate() {
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
}
data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID, req.Variant)
switch {
case errors.Is(err, service.ErrAttachmentNotReady):
httpx.WriteError(w, http.StatusConflict, dto.ErrorCodeConflict, "attachment not ready", requestID)
return
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
case err != nil:
httpx.WriteInternalError(w, requestID, err)
return
}
w.Header().Set("Content-Type", string(contentType))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(data)
}
+80
View File
@@ -0,0 +1,80 @@
package handler
import (
"errors"
"net/http"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/internal/service"
)
type AuthHandler struct {
service *service.AuthService
}
func NewAuthHandler(s *service.AuthService) *AuthHandler {
return &AuthHandler{service: s}
}
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
username, plain, ok := r.BasicAuth()
if !ok {
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
return
}
if !httpx.RejectBody(w, r, requestID) {
return
}
session, err := h.service.Login(r.Context(), username, plain)
if errors.Is(err, service.ErrInvalidCredentials) {
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
return
}
if err != nil {
httpx.WriteInternalError(w, requestID, err)
return
}
httpx.WriteJSON(w, http.StatusCreated, dto.SessionResponse{
Token: session.Token,
TokenType: "Bearer",
ExpiresAt: session.ExpiresAt,
User: dto.UserResponse{
ID: session.User.ID,
Username: session.User.Username,
DisplayName: session.User.DisplayName,
CreatedAt: session.User.CreatedAt,
},
})
}
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
token, ok := httpx.BearerToken(r)
if !ok {
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
err := h.service.Logout(r.Context(), token)
switch {
case errors.Is(err, service.ErrSessionCacheUnavailable):
httpx.WriteError(w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, "session cache unavailable", requestID)
return
case errors.Is(err, service.ErrUnauthorized):
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
case err != nil:
httpx.WriteInternalError(w, requestID, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+150
View File
@@ -0,0 +1,150 @@
package handler
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/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(r.Context(), 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.WriteInternalError(w, requestID, err)
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(r.Context(), 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.WriteInternalError(w, requestID, err)
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(r.Context(), 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.WriteInternalError(w, requestID, err)
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,
})
}
+62
View File
@@ -0,0 +1,62 @@
package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
)
const readyPingTimeout = 2 * time.Second
type Pinger interface {
Ping(ctx context.Context) error
}
type HealthHandler struct {
log *slog.Logger
dependencies []Pinger
}
func NewHealthHandler(log *slog.Logger, dependencies ...Pinger) *HealthHandler {
return &HealthHandler{log: log, dependencies: dependencies}
}
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()
for _, dependency := range h.dependencies {
if err := dependency.Ping(ctx); err != nil {
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
httpx.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",
})
}
+188
View File
@@ -0,0 +1,188 @@
package handler
import (
"errors"
"net/http"
"regexp"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/internal/service"
)
var idempotencyKeyReq = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
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
}
key := r.Header.Get("Idempotency-Key")
if !idempotencyKeyReq.MatchString(key) {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid Idempotency-Key",
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
}
attachmentIDs := make([]uuid.UUID, 0, len(req.AttachmentIDs))
for _, s := range req.AttachmentIDs {
id, err := uuid.Parse(s)
if err != nil {
httpx.WriteError(
w,
http.StatusBadRequest,
dto.ErrorCodeInvalidRequest,
"invalid attachment_id",
requestID,
)
return
}
attachmentIDs = append(attachmentIDs, id)
}
message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text, attachmentIDs)
switch {
case errors.Is(err, service.ErrMessageChatNotFound):
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"chat not found",
requestID,
)
return
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"attachment not found",
requestID,
)
return
case errors.Is(err, service.ErrAttachmentNotReady):
httpx.WriteError(
w,
http.StatusConflict,
dto.ErrorCodeConflict,
"attachment not ready",
requestID,
)
return
case errors.Is(err, service.ErrIdempotencyKeyConflict):
httpx.WriteError(
w,
http.StatusConflict,
dto.ErrorCodeConflict,
"idempotency key reused with different request",
requestID,
)
return
case err != nil:
httpx.WriteInternalError(w, requestID, err)
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(r.Context(), 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.WriteInternalError(w, requestID, err)
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,
})
}
+95
View File
@@ -0,0 +1,95 @@
package handler
import (
"errors"
"net/http"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/middleware"
"gavrilenko-sxdees/lab7/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(
r.Context(),
req.Username,
req.DisplayName,
req.Password,
)
if errors.Is(err, service.ErrUsernameTaken) {
httpx.WriteError(
w,
http.StatusConflict,
dto.ErrorCodeConflict,
"username already taken",
requestID,
)
return
}
if err != nil {
httpx.WriteInternalError(w, requestID, err)
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(r.Context(), userID)
if errors.Is(err, service.ErrUserNotFound) {
httpx.WriteError(
w,
http.StatusNotFound,
dto.ErrorCodeNotFound,
"user not found",
requestID,
)
return
}
if err != nil {
httpx.WriteInternalError(w, requestID, err)
return
}
httpx.WriteJSON(w, http.StatusOK, dto.UserResponse{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: user.CreatedAt,
})
}
+37
View File
@@ -0,0 +1,37 @@
package httpx
import (
"net/http"
"strings"
"gavrilenko-sxdees/lab7/internal/dto"
)
const (
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
BearerChallenge = `Bearer realm="messenger"`
)
func BearerToken(r *http.Request) (string, bool) {
const prefix = "Bearer "
header := r.Header.Get("Authorization")
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
return "", false
}
token := strings.TrimSpace(header[len(prefix):])
return token, token != ""
}
func WriteUnauthorized(w http.ResponseWriter, challenge, requestID string) {
w.Header().Set("WWW-Authenticate", challenge)
WriteError(
w,
http.StatusUnauthorized,
dto.ErrorCodeUnauthorized,
"unauthorized",
requestID,
)
}
+34
View File
@@ -0,0 +1,34 @@
package httpx
import (
"net/http"
"strconv"
"gavrilenko-sxdees/lab7/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
}
+49
View File
@@ -0,0 +1,49 @@
package httpx
import (
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"gavrilenko-sxdees/lab7/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
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
return false
}
return true
}
func RejectBody(w http.ResponseWriter, r *http.Request, requestID string) bool {
if r.Body == nil || r.Body == http.NoBody {
return true
}
var b [1]byte
if n, _ := r.Body.Read(b[:]); n > 0 {
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
return false
}
return true
}
+68
View File
@@ -0,0 +1,68 @@
package httpx
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strings"
"github.com/jackc/pgx/v5/pgconn"
"gavrilenko-sxdees/lab7/internal/dto"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
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,
},
})
}
func WriteInternalError(w http.ResponseWriter, requestID string, err error) {
if isUnavailable(err) {
WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"dependency unavailable",
requestID,
)
return
}
WriteError(
w,
http.StatusInternalServerError,
dto.ErrorCodeInternalError,
"internal server error",
requestID,
)
}
func isUnavailable(err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, s3store.ErrUnavailable) {
return true
}
if _, ok := errors.AsType[net.Error](err); ok {
return true
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
return strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57P01"
}
return false
}
+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,
}),
)
}
+50
View File
@@ -0,0 +1,50 @@
package middleware
import (
"context"
"errors"
"net/http"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/httpx"
"gavrilenko-sxdees/lab7/internal/service"
)
type userIDContextKey struct{}
type authenticator interface {
Authenticate(ctx context.Context, token string) (uuid.UUID, error)
}
func Auth(auth authenticator) 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())
token, ok := httpx.BearerToken(r)
if !ok {
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
userID, err := auth.Authenticate(r.Context(), token)
if errors.Is(err, service.ErrUnauthorized) {
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
if err != nil {
httpx.WriteInternalError(w, requestID, err)
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"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/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()),
)
}
})
}
}
+14
View File
@@ -0,0 +1,14 @@
package middleware
import (
"net/http"
)
func InstanceID(id string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}
}
+53
View File
@@ -0,0 +1,53 @@
package middleware
import (
"log/slog"
"net/http"
"time"
)
type responseWriter struct {
http.ResponseWriter
status int
}
func (w *responseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
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(),
)
})
}
}
+68
View File
@@ -0,0 +1,68 @@
package middleware
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
)
const (
loginLimitKeyPrefix = "login:attempt:"
loginLimitWindow = time.Minute
loginLimitMax = 20
)
type LoginLimiter struct {
rdb *redis.Client
}
func NewLoginLimiter(rdb *redis.Client) *LoginLimiter {
return &LoginLimiter{rdb: rdb}
}
func (l *LoginLimiter) Limit(next http.Handler) http.Handler {
if l == nil || l.rdb == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/v1/auth/sessions" {
next.ServeHTTP(w, r)
return
}
username, _, ok := r.BasicAuth()
if !ok {
next.ServeHTTP(w, r)
return
}
key := loginLimitKeyPrefix + username
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
defer cancel()
n, err := l.rdb.Incr(ctx, key).Result()
if err != nil {
next.ServeHTTP(w, r)
return
}
if n == 1 {
_ = l.rdb.Expire(ctx, key, loginLimitWindow).Err()
}
if n > loginLimitMax {
ttl, _ := l.rdb.TTL(ctx, key).Result()
if ttl < 0 {
ttl = loginLimitWindow
}
w.Header().Set("Retry-After", strconv.Itoa(int(ttl.Seconds())))
httpx.WriteError(w, http.StatusTooManyRequests, dto.ErrorCodeRateLimited,
fmt.Sprintf("too many login attempts; retry in %ds", int(ttl.Seconds())),
GetRequestID(r.Context()))
return
}
next.ServeHTTP(w, r)
})
}
+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
}
+46
View File
@@ -0,0 +1,46 @@
package middleware
import (
"net/http"
"time"
"go.opentelemetry.io/otel/trace"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func Telemetry() 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()
ctx, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer)
defer span.End()
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(writer, r.WithContext(ctx))
route := telemetry.RoutePattern(r)
if route == "/health/live" || route == "/health/ready" {
return
}
telemetry.HTTP(ctx, r.Method, route, writer.status, time.Since(start).Seconds())
if tid := telemetry.TraceID(ctx); tid != "" && tid != "00000000000000000000000000000000" {
w.Header().Set("X-Trace-Id", tid)
}
})
}
}
+17
View File
@@ -0,0 +1,17 @@
package middleware
import (
"context"
"net/http"
"time"
)
func RequestTimeout(d time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), d)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
+60
View File
@@ -0,0 +1,60 @@
package model
import (
"time"
"github.com/google/uuid"
)
type ContentType string
const (
ContentTypePNG ContentType = "image/png"
ContentTypeJPEG ContentType = "image/jpeg"
ContentTypeWebP ContentType = "image/webp"
)
type AttachmentStatus string
const (
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
)
const AttachmentContentOriginal = "original"
type AttachmentVariantName string
const (
AttachmentVariantNameThumbnail AttachmentVariantName = "thumbnail"
AttachmentVariantNameCrop AttachmentVariantName = "crop"
AttachmentVariantNameOptimized AttachmentVariantName = "optimized"
)
type AttachmentVariant struct {
Name AttachmentVariantName
ContentType ContentType
SizeBytes int
Width int
Height int
Sha256 string
}
type Attachment struct {
Variants []AttachmentVariant
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType ContentType
SizeBytes int
Sha256 string
Status AttachmentStatus
Width *int32
Height *int32
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
+19
View File
@@ -0,0 +1,19 @@
package model
import (
"time"
"github.com/google/uuid"
)
type AttachmentJob struct {
SchemaVersion int `json:"schema_version"`
JobID uuid.UUID `json:"job_id"`
Type string `json:"type"`
AttachmentID uuid.UUID `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
+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
}
+16
View File
@@ -0,0 +1,16 @@
package model
import (
"time"
"github.com/google/uuid"
)
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
AttachmentIDs []uuid.UUID
CreatedAt time.Time
}
+9
View File
@@ -0,0 +1,9 @@
package model
import "time"
type Session struct {
Token string
ExpiresAt time.Time
User User
}
+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
}
+127
View File
@@ -0,0 +1,127 @@
package openbao
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
// VerifyAppRole proves service authentication against OpenBao (no root token in app).
func VerifyAppRole(ctx context.Context, role string) error {
addr := strings.TrimRight(os.Getenv("BAO_ADDR"), "/")
if addr == "" {
return nil
}
roleID, err := readFile(os.Getenv("BAO_ROLE_ID_FILE"))
if err != nil || strings.HasPrefix(roleID, "00000000") || roleID == "bootstrap-pending" {
return fmt.Errorf("openbao approle not bootstrapped")
}
secretID, err := readFile(os.Getenv("BAO_SECRET_ID_FILE"))
if err != nil {
return err
}
caPath := os.Getenv("BAO_CACERT")
if caPath == "" {
caPath = "/run/secrets/ca_cert"
}
client, err := httpClient(caPath)
if err != nil {
return err
}
body := fmt.Sprintf(`{"role_id":%q,"secret_id":%q}`, roleID, secretID)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, addr+"/v1/auth/approle/login", strings.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("approle login: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("approle login status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
}
var login struct {
Auth struct {
ClientToken string `json:"client_token"`
} `json:"auth"`
}
if err := json.NewDecoder(resp.Body).Decode(&login); err != nil {
return err
}
token := login.Auth.ClientToken
if token == "" {
return fmt.Errorf("empty openbao token")
}
path := os.Getenv("BAO_VERIFY_KV_PATH")
if path == "" {
if role == "worker" {
path = "messenger/worker/stand"
} else {
path = "messenger/api/stand"
}
}
req2, err := http.NewRequestWithContext(ctx, http.MethodGet, addr+"/v1/secret/data/"+path, nil)
if err != nil {
return err
}
req2.Header.Set("X-Vault-Token", token)
resp2, err := client.Do(req2)
if err != nil {
return err
}
defer resp2.Body.Close()
if resp2.StatusCode == http.StatusNotFound {
return nil
}
if resp2.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp2.Body)
return fmt.Errorf("kv read status %d: %s", resp2.StatusCode, strings.TrimSpace(string(b)))
}
return nil
}
func readFile(path string) (string, error) {
if path == "" {
return "", fmt.Errorf("empty path")
}
b, err := os.ReadFile(path)
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
func httpClient(caPath string) (*http.Client, error) {
caPEM, err := os.ReadFile(caPath)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, fmt.Errorf("parse bao ca")
}
serverName := os.Getenv("BAO_TLS_SERVER_NAME")
if serverName == "" {
serverName = "openbao.messenger.lab"
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
MinVersion: tls.VersionTLS12,
ServerName: serverName,
},
}
return &http.Client{Transport: tr, Timeout: 5 * time.Second}, nil
}
+139
View File
@@ -0,0 +1,139 @@
package outbox
import (
"context"
"encoding/json"
"log/slog"
"time"
"github.com/jackc/pgx/v5/pgxpool"
amqp "github.com/rabbitmq/amqp091-go"
"go.opentelemetry.io/otel/trace"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/rabbitmq"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
const (
pollInterval = time.Second
retryInterval = 2 * time.Second
publishTimeout = 5 * time.Second
)
type Publisher struct {
pool *pgxpool.Pool
url string
log *slog.Logger
}
func NewPublisher(pool *pgxpool.Pool, url string, log *slog.Logger) *Publisher {
return &Publisher{
pool: pool,
url: url,
log: log,
}
}
func (p *Publisher) Run(ctx context.Context) {
for ctx.Err() == nil {
client, err := rabbitmq.New(p.url)
if err == nil {
p.log.Info("outbox publisher connected")
err = p.publish(ctx, client)
_ = client.Close()
}
if ctx.Err() != nil {
return
}
p.log.Error("outbox publisher retry", "error", err)
if !wait(ctx, retryInterval) {
return
}
}
}
func (p *Publisher) publish(ctx context.Context, client *rabbitmq.Client) error {
for ctx.Err() == nil {
published, err := p.publishOne(ctx, client)
if err != nil {
return err
}
if !published && !wait(ctx, pollInterval) {
return ctx.Err()
}
}
return ctx.Err()
}
func (p *Publisher) publishOne(ctx context.Context, client *rabbitmq.Client) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, publishTimeout)
defer cancel()
tx, err := p.pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx)
q := db.New(tx)
rows, err := q.LockPendingOutboxEntries(ctx, 1)
if err != nil {
return false, err
}
if len(rows) == 0 {
return false, nil
}
row := rows[0]
publishCtx, span := telemetry.Start(
telemetry.Extract(ctx, row.Traceparent, row.Tracestate),
"queue.publish",
trace.SpanKindProducer,
)
defer span.End()
body, err := json.Marshal(model.AttachmentJob{
SchemaVersion: 1,
JobID: row.JobID,
Type: "attachment.process.v1",
AttachmentID: row.AttachmentID,
PipelineVersion: row.PipelineVersion,
Attempt: row.Attempt,
CreatedAt: row.CreatedAt.UTC(),
Traceparent: row.Traceparent,
Tracestate: row.Tracestate,
})
if err != nil {
return false, err
}
parent, state := telemetry.Inject(publishCtx)
headers := amqp.Table{}
if parent != "" {
headers["traceparent"] = parent
}
if state != "" {
headers["tracestate"] = state
}
if err := client.Publish(publishCtx, row.JobID.String(), body, headers); err != nil {
return false, err
}
if _, err := q.MarkOutboxPublished(ctx, row.ID); err != nil {
return false, err
}
if err := tx.Commit(ctx); err != nil {
return false, err
}
return true, nil
}
func wait(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
+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
}
+120
View File
@@ -0,0 +1,120 @@
package rabbitmq
import (
"context"
"errors"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"gavrilenko-sxdees/lab7/internal/tlsconfig"
)
const QueueName = "attachments.process.v1"
var (
ErrConnect = errors.New("connect to rabbitmq")
ErrNotRouted = errors.New("rabbitmq message not routed")
ErrNack = errors.New("rabbitmq publish rejected")
ErrPrefetch = errors.New("rabbitmq prefetch must be positive")
)
type Client struct {
conn *amqp.Connection
channel *amqp.Channel
returns <-chan amqp.Return
}
func New(url string) (*Client, error) {
cfg := amqp.Config{}
tlsCfg, err := tlsconfig.ClientTLSFromEnv("BROKER_TLS")
if err != nil {
return nil, err
}
if tlsCfg != nil {
cfg.TLSClientConfig = tlsCfg
} else {
cfg.Dial = amqp.DefaultDial(5 * time.Second)
}
conn, err := amqp.DialConfig(url, cfg)
if err != nil {
return nil, ErrConnect
}
channel, err := conn.Channel()
if err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
if _, err := channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
if err := channel.Confirm(false); err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
return &Client{
conn: conn,
channel: channel,
returns: channel.NotifyReturn(make(chan amqp.Return, 1)),
}, nil
}
// Publish must not be called concurrently on the same client.
func (c *Client) Publish(ctx context.Context, messageID string, body []byte, headers amqp.Table) error {
if err := ctx.Err(); err != nil {
return err
}
stop := context.AfterFunc(ctx, func() {
_ = c.conn.CloseDeadline(time.Now())
})
defer stop()
if headers == nil {
headers = amqp.Table{}
}
confirmation, err := c.channel.PublishWithDeferredConfirm("", QueueName, true, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: messageID,
Headers: headers,
Body: body,
})
if err != nil {
return err
}
ack, err := confirmation.WaitContext(ctx)
if err != nil {
return err
}
if !ack {
return ErrNack
}
select {
case _, ok := <-c.returns:
if !ok {
return amqp.ErrClosed
}
return ErrNotRouted
default:
return nil
}
}
func (c *Client) Consume(ctx context.Context, prefetch int) (<-chan amqp.Delivery, error) {
if prefetch < 1 {
return nil, ErrPrefetch
}
if err := c.channel.Qos(prefetch, 0, false); err != nil {
return nil, err
}
return c.channel.ConsumeWithContext(ctx, QueueName, "", false, false, false, false, nil)
}
func (c *Client) Close() error {
return c.conn.CloseDeadline(time.Now().Add(time.Second))
}
+323
View File
@@ -0,0 +1,323 @@
package reconcile
import (
"context"
"fmt"
"log/slog"
"sort"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gavrilenko-sxdees/lab7/internal/db"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
const (
Prefix = "chats/"
StagingPrefix = "staging/"
DefaultStagingRetention = 24 * time.Hour
DefaultGrace = time.Hour
DefaultMaxDeletes = 100
ErrorCodeObjectMissing = "object_missing"
)
type Options struct {
DryRun bool
Grace time.Duration
MaxDeletes int
StagingRetention time.Duration
}
type Report struct {
ScannedObjects int `json:"scanned_objects"`
ScannedRows int `json:"scanned_rows"`
ListPages int `json:"list_pages"`
StagingObjects []string `json:"staging_objects"`
OrphanObjects []string `json:"orphan_objects"`
MissingAttachments []uuid.UUID `json:"missing_attachments"`
CorruptObjects []string `json:"corrupt_objects"`
SkippedFresh int `json:"skipped_fresh"`
SkippedInactive int `json:"skipped_inactive"`
DeletedObjects int `json:"deleted_objects"`
MarkedFailed int `json:"marked_failed"`
DryRun bool `json:"dry_run"`
Errors []string `json:"errors"`
DurationMS int64 `json:"duration_ms"`
}
type ObjectClient interface {
ListAll(ctx context.Context, prefix string) (s3store.ListResult, error)
DeleteAdmin(ctx context.Context, key string) error
}
type txBeginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
}
type AttachmentQueries interface {
LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (db.Attachment, error)
ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error
ListAttachmentsForReconcile(ctx context.Context) ([]db.ListAttachmentsForReconcileRow, error)
MarkAttachmentFailedIfReady(ctx context.Context, arg db.MarkAttachmentFailedIfReadyParams) (int64, error)
}
type Reconciler struct {
pool txBeginner
q AttachmentQueries
withTx func(pgx.Tx) AttachmentQueries
store ObjectClient
log *slog.Logger
now func() time.Time
}
type plan struct {
orphans []s3store.ObjectInfo
staging []s3store.ObjectInfo
missing []db.ListAttachmentsForReconcileRow
corrupt []s3store.ObjectInfo
skippedFresh int
skippedInactive int
}
func New(
pool *pgxpool.Pool,
store ObjectClient,
queries *db.Queries,
log *slog.Logger,
) *Reconciler {
if log == nil {
log = slog.Default()
}
return &Reconciler{
pool: pool,
withTx: func(tx pgx.Tx) AttachmentQueries {
return queries.WithTx(tx)
},
store: store,
q: queries,
log: log,
now: time.Now,
}
}
func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
opts = opts.withDefaults()
started := r.now()
report := Report{
OrphanObjects: []string{},
StagingObjects: []string{},
MissingAttachments: []uuid.UUID{},
CorruptObjects: []string{},
DryRun: opts.DryRun,
Errors: []string{},
}
listed, err := r.store.ListAll(ctx, Prefix)
if err != nil {
return report, err
}
staging, err := r.store.ListAll(ctx, StagingPrefix)
if err != nil {
return report, err
}
rows, err := r.q.ListAttachmentsForReconcile(ctx)
if err != nil {
return report, err
}
report.ScannedObjects = len(listed.Objects) + len(staging.Objects)
report.ScannedRows = len(rows)
report.ListPages = listed.Pages + staging.Pages
p := buildPlan(listed.Objects, staging.Objects, rows, started, opts)
for _, obj := range p.orphans {
report.OrphanObjects = append(report.OrphanObjects, obj.Key)
}
for _, obj := range p.staging {
report.StagingObjects = append(report.StagingObjects, obj.Key)
}
for _, obj := range p.corrupt {
report.CorruptObjects = append(report.CorruptObjects, obj.Key)
}
for _, row := range p.missing {
report.MissingAttachments = append(report.MissingAttachments, row.ID)
}
report.SkippedFresh = p.skippedFresh
report.SkippedInactive = p.skippedInactive
if !opts.DryRun {
r.apply(ctx, opts, p, &report)
}
report.DurationMS = r.now().Sub(started).Milliseconds()
r.log.Info(
"attachment reconcile finished",
"dry_run", opts.DryRun,
"scanned_objects", report.ScannedObjects,
"scanned_rows", report.ScannedRows,
"list_pages", report.ListPages,
"orphan_objects", len(report.OrphanObjects),
"staging_objects", len(report.StagingObjects),
"missing_attachments", len(report.MissingAttachments),
"corrupt_objects", len(report.CorruptObjects),
"deleted_objects", report.DeletedObjects,
"marked_failed", report.MarkedFailed,
"errors", len(report.Errors),
)
return report, nil
}
func (o Options) withDefaults() Options {
if o.Grace <= 0 {
o.Grace = DefaultGrace
}
if o.MaxDeletes <= 0 {
o.MaxDeletes = DefaultMaxDeletes
}
if o.StagingRetention <= 0 {
o.StagingRetention = DefaultStagingRetention
}
return o
}
func buildPlan(
objects []s3store.ObjectInfo,
staging []s3store.ObjectInfo,
rows []db.ListAttachmentsForReconcileRow,
now time.Time,
opts Options,
) plan {
var p plan
byKey := make(map[string]s3store.ObjectInfo, len(objects))
for _, obj := range objects {
byKey[obj.Key] = obj
}
byStagingKey := make(map[string]db.ListAttachmentsForReconcileRow, len(rows))
for _, row := range rows {
if row.StagingKey != nil {
byStagingKey[*row.StagingKey] = row
}
obj, exists := byKey[row.S3Key]
if exists {
delete(byKey, row.S3Key)
}
switch row.Status {
case db.AttachmentStatusQueued:
p.skippedInactive++
case db.AttachmentStatusReady:
if !exists {
p.missing = append(p.missing, row)
continue
}
if obj.Size != int64(row.SizeBytes) {
p.corrupt = append(p.corrupt, obj)
}
default:
if exists {
p.skippedInactive++
}
}
}
for _, obj := range byKey {
if now.Sub(obj.LastModified) < opts.Grace {
p.skippedFresh++
continue
}
p.orphans = append(p.orphans, obj)
}
for _, obj := range staging {
retainedSince := obj.LastModified
if row, exists := byStagingKey[obj.Key]; exists {
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
p.skippedInactive++
continue
}
retainedSince = row.UpdatedAt
}
if now.Sub(retainedSince) < opts.StagingRetention {
p.skippedFresh++
continue
}
p.staging = append(p.staging, obj)
}
sort.Slice(p.staging, func(i, j int) bool {
return p.staging[i].Key < p.staging[j].Key
})
sort.Slice(p.orphans, func(i, j int) bool {
return p.orphans[i].Key < p.orphans[j].Key
})
sort.Slice(p.corrupt, func(i, j int) bool {
return p.corrupt[i].Key < p.corrupt[j].Key
})
sort.Slice(p.missing, func(i, j int) bool {
return p.missing[i].ID.String() < p.missing[j].ID.String()
})
return p
}
func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Report) {
deletes := 0
for _, obj := range p.orphans {
if deletes >= opts.MaxDeletes {
report.Errors = append(report.Errors, "max deletes reached")
break
}
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", obj.Key, err))
continue
}
deletes++
report.DeletedObjects++
}
for _, row := range p.missing {
marked, err := r.q.MarkAttachmentFailedIfReady(ctx, db.MarkAttachmentFailedIfReadyParams{
ID: row.ID,
ErrorCode: ErrorCodeObjectMissing,
})
if err != nil {
report.Errors = append(report.Errors, fmt.Sprintf("mark failed %s: %v", row.ID, err))
continue
}
report.MarkedFailed += int(marked)
}
for _, obj := range p.staging {
if report.DeletedObjects >= opts.MaxDeletes {
report.Errors = append(report.Errors, "max deletes reached")
break
}
if err := r.cleanupStagingObject(ctx, obj, opts, report); err != nil {
report.Errors = append(report.Errors, fmt.Sprintf("cleanup staging %s: %v", obj.Key, err))
}
}
}
+60
View File
@@ -0,0 +1,60 @@
package reconcile
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"gavrilenko-sxdees/lab7/internal/db"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
func (r *Reconciler) cleanupStagingObject(
ctx context.Context,
obj s3store.ObjectInfo,
opts Options,
report *Report,
) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
tx, err := r.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := r.withTx(tx)
row, err := q.LockAttachmentByStagingKey(ctx, obj.Key)
orphan := errors.Is(err, pgx.ErrNoRows)
if err != nil && !orphan {
return err
}
if !orphan {
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
report.SkippedInactive++
return nil
}
if r.now().Sub(row.UpdatedAt) < opts.StagingRetention {
report.SkippedFresh++
return nil
}
}
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
return err
}
report.DeletedObjects++
if !orphan {
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
return err
}
}
return tx.Commit(ctx)
}
+32
View File
@@ -0,0 +1,32 @@
package redis
import (
"context"
"fmt"
"log/slog"
"time"
goredis "github.com/redis/go-redis/v9"
)
func New(ctx context.Context, log *slog.Logger, url string) (*goredis.Client, error) {
opts, err := goredis.ParseURL(url)
if err != nil {
return nil, fmt.Errorf("parse redis url: %w", err)
}
opts.DialTimeout = 1 * time.Second
opts.ReadTimeout = 200 * time.Millisecond
opts.WriteTimeout = 200 * time.Millisecond
opts.MaxRetries = -1
client := goredis.NewClient(opts)
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err := client.Ping(pingCtx).Err(); err != nil {
log.Warn("redis unavailable, running without cache", "error", err)
}
return client, nil
}
+301
View File
@@ -0,0 +1,301 @@
package s3
import (
"context"
"errors"
"io"
"log/slog"
"net"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
appconfig "gavrilenko-sxdees/lab7/internal/config"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
var (
ErrUnavailable = errors.New("s3 unavailable")
ErrLoadConfig = errors.New("load aws config")
ErrHeadBucket = errors.New("head bucket")
ErrCreateBucket = errors.New("create bucket")
ErrObjectNotFound = errors.New("object not found")
ErrPutObject = errors.New("put object")
ErrGetObject = errors.New("get object")
ErrListObjects = errors.New("list objects")
ErrDeleteObject = errors.New("delete object")
)
type Client struct {
bucket string
bootstrap *awss3.Client
api *awss3.Client
log *slog.Logger
}
type ObjectInfo struct {
Key string
Size int64
LastModified time.Time
}
type ListResult struct {
Objects []ObjectInfo
Pages int
}
func New(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) {
c, err := NewAPI(ctx, cfg, log)
if err != nil {
return nil, err
}
bootstrapAccessKey, err := cfg.BootstrapAccessKey()
if err != nil {
log.Error("read s3 bootstrap access key", "error", err)
return nil, err
}
bootstrapSecretKey, err := cfg.BootstrapSecretKey()
if err != nil {
log.Error("read s3 bootstrap secret key", "error", err)
return nil, err
}
c.bootstrap, err = newS3Client(ctx, log, cfg.Endpoint, cfg.Region, bootstrapAccessKey, bootstrapSecretKey)
if err != nil {
return nil, err
}
return c, nil
}
func NewAPI(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) {
apiAccessKey, err := cfg.APIAccessKey()
if err != nil {
log.Error("read s3 api access key", "error", err)
return nil, err
}
apiSecretKey, err := cfg.APISecretKey()
if err != nil {
log.Error("read s3 api secret key", "error", err)
return nil, err
}
api, err := newS3Client(ctx, log, cfg.Endpoint, cfg.Region, apiAccessKey, apiSecretKey)
if err != nil {
return nil, err
}
return &Client{
bucket: cfg.Bucket,
api: api,
log: log,
}, nil
}
func (c *Client) Bucket() string {
return c.bucket
}
func (c *Client) EnsureBucket(ctx context.Context) error {
_, err := c.bootstrap.HeadBucket(ctx, &awss3.HeadBucketInput{
Bucket: aws.String(c.bucket),
})
if err == nil {
return nil
}
if !isNotFound(err) {
c.log.Error("head bucket", "bucket", c.bucket, "error", err)
return ErrHeadBucket
}
_, err = c.bootstrap.CreateBucket(ctx, &awss3.CreateBucketInput{
Bucket: aws.String(c.bucket),
})
if err == nil || isAlreadyExists(err) {
return nil
}
c.log.Error("create bucket", "bucket", c.bucket, "error", err)
return ErrCreateBucket
}
func (c *Client) Ping(ctx context.Context) error {
_, err := c.api.HeadBucket(ctx, &awss3.HeadBucketInput{Bucket: aws.String(c.bucket)})
if err != nil {
c.log.Error("head bucket", "bucket", c.bucket, "error", err)
return operationError(ErrHeadBucket, err)
}
return nil
}
func (c *Client) Put(
ctx context.Context,
key string,
body io.ReadSeeker,
size int64,
contentType string,
) error {
_, err := c.api.PutObject(ctx, &awss3.PutObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
Body: body,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
if err != nil {
c.log.Error("put object", "bucket", c.bucket, "key", key, "error", err)
return operationError(ErrPutObject, err)
}
return nil
}
func (c *Client) Get(ctx context.Context, key string) (*awss3.GetObjectOutput, error) {
out, err := c.api.GetObject(ctx, &awss3.GetObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
})
if isNotFound(err) {
c.log.Warn("get object", "bucket", c.bucket, "key", key, "error", err)
return nil, ErrObjectNotFound
}
if err != nil {
c.log.Error("get object", "bucket", c.bucket, "key", key, "error", err)
return nil, operationError(ErrGetObject, err)
}
return out, nil
}
func (c *Client) ListAll(ctx context.Context, prefix string) (ListResult, error) {
result := ListResult{Objects: []ObjectInfo{}}
paginator := awss3.NewListObjectsV2Paginator(c.bootstrap, &awss3.ListObjectsV2Input{
Bucket: aws.String(c.bucket),
Prefix: aws.String(prefix),
})
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
c.log.Error("list objects", "bucket", c.bucket, "prefix", prefix, "error", err)
return ListResult{}, ErrListObjects
}
result.Pages++
for _, obj := range page.Contents {
result.Objects = append(result.Objects, ObjectInfo{
Key: aws.ToString(obj.Key),
Size: aws.ToInt64(obj.Size),
LastModified: aws.ToTime(obj.LastModified),
})
}
}
return result, nil
}
func (c *Client) DeleteAdmin(ctx context.Context, key string) error {
return c.deleteObject(ctx, c.bootstrap, key)
}
func (c *Client) Delete(ctx context.Context, key string) error {
return c.deleteObject(ctx, c.api, key)
}
func (c *Client) deleteObject(ctx context.Context, client *awss3.Client, key string) error {
_, err := client.DeleteObject(ctx, &awss3.DeleteObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
})
if isNotFound(err) {
return nil
}
if err != nil {
c.log.Error("delete object", "bucket", c.bucket, "key", key, "error", err)
return ErrDeleteObject
}
return nil
}
func newS3Client(
ctx context.Context,
log *slog.Logger,
endpoint string,
region string,
accessKey string,
secretKey string,
) (*awss3.Client, error) {
httpClient := &http.Client{
Transport: telemetry.Transport(http.DefaultTransport),
Timeout: 30 * time.Second,
}
cfg, err := awsconfig.LoadDefaultConfig(
ctx,
awsconfig.WithRegion(region),
awsconfig.WithHTTPClient(httpClient),
awsconfig.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""),
),
)
if err != nil {
log.Error("load aws config", "endpoint", endpoint, "region", region, "error", err)
return nil, ErrLoadConfig
}
return awss3.NewFromConfig(cfg, func(o *awss3.Options) {
o.BaseEndpoint = aws.String(endpoint)
o.UsePathStyle = true
}), nil
}
func operationError(operation, err error) error {
var networkError net.Error
var responseError *awshttp.ResponseError
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) ||
(errors.As(err, &responseError) && responseError.HTTPStatusCode() >= 500) {
return ErrUnavailable
}
return operation
}
func isNotFound(err error) bool {
var responseErr *awshttp.ResponseError
if errors.As(err, &responseErr) && responseErr.HTTPStatusCode() == http.StatusNotFound {
return true
}
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NotFound", "NoSuchBucket", "NoSuchKey":
return true
}
}
return false
}
func isAlreadyExists(err error) bool {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
return true
}
}
return false
}
+99
View File
@@ -0,0 +1,99 @@
package s3
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"gavrilenko-sxdees/lab7/internal/config"
)
const (
seaweedUID = 1000
seaweedGID = 1000
)
type Credential struct {
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
}
type Identity struct {
Name string `json:"name"`
Credentials []Credential `json:"credentials"`
Actions []string `json:"actions"`
}
type Config struct {
Identities []Identity `json:"identities"`
}
func WriteConfig(output string, cfg config.S3Config) error {
apiAccessKey, err := cfg.APIAccessKey()
if err != nil {
return err
}
apiSecretKey, err := cfg.APISecretKey()
if err != nil {
return err
}
bootstrapAccessKey, err := cfg.BootstrapAccessKey()
if err != nil {
return err
}
bootstrapSecretKey, err := cfg.BootstrapSecretKey()
if err != nil {
return err
}
config := Config{
Identities: []Identity{
{
Name: "bootstrap",
Credentials: []Credential{
{AccessKey: bootstrapAccessKey, SecretKey: bootstrapSecretKey},
},
Actions: []string{"Admin", "Read", "Write", "List", "Tagging"},
},
{
Name: "api",
Credentials: []Credential{
{AccessKey: apiAccessKey, SecretKey: apiSecretKey},
},
Actions: []string{"Read", "Write", "List", "Tagging"},
},
},
}
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("marshal s3 config: %w", err)
}
if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
tmp := output + ".tmp"
if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil {
return fmt.Errorf("write config: %w", err)
}
if err := os.Chown(tmp, seaweedUID, seaweedGID); err != nil {
return fmt.Errorf("chown config: %w", err)
}
if err := os.Chmod(tmp, 0o400); err != nil {
return fmt.Errorf("chmod config: %w", err)
}
if err := os.Rename(tmp, output); err != nil {
return fmt.Errorf("replace config: %w", err)
}
return nil
}
+362
View File
@@ -0,0 +1,362 @@
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"net"
"net/http"
"os"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/postgres"
s3store "gavrilenko-sxdees/lab7/internal/s3"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
var (
ErrAttachmentNotFound = errors.New("attachment not found")
ErrAttachmentNotReady = errors.New("attachment not ready")
ErrInvalidImage = errors.New("invalid image")
ErrInvalidSize = errors.New("invalid size")
ErrUploadReadTimeout = errors.New("upload body read timed out")
)
type attachmentQueries interface {
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
CreateOutboxEntry(ctx context.Context, arg db.CreateOutboxEntryParams) (db.Outbox, error)
GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error)
ListAttachmentVariants(ctx context.Context, arg db.ListAttachmentVariantsParams) ([]db.AttachmentVariant, error)
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
}
type AttachmentService struct {
pool txBeginner
q attachmentQueries
withTx func(pgx.Tx) attachmentQueries
s3 *s3store.Client
maxBytes int
maxPixels int
decodeSlot chan struct{}
}
func NewAttachmentService(
pool *pgxpool.Pool,
q *db.Queries,
s3 *s3store.Client,
maxBytes, maxPixels int,
) *AttachmentService {
return &AttachmentService{
pool: pool,
q: q,
withTx: func(tx pgx.Tx) attachmentQueries {
return q.WithTx(tx)
},
s3: s3,
maxBytes: maxBytes,
maxPixels: maxPixels,
decodeSlot: make(chan struct{}, 1),
}
}
func (s *AttachmentService) Upload(
ctx context.Context,
userID, chatID uuid.UUID,
filename string,
body io.Reader,
contentType string,
) (model.Attachment, error) {
if err := s.ensureMember(ctx, userID, chatID); err != nil {
return model.Attachment{}, err
}
tmp, err := os.CreateTemp("", "upload-*.tmp")
if err != nil {
return model.Attachment{}, err
}
defer func() {
_ = tmp.Close()
_ = os.Remove(tmp.Name())
}()
hasher := sha256.New()
size, err := io.Copy(io.MultiWriter(tmp, hasher), body)
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
return model.Attachment{}, ErrInvalidSize
}
var networkErr net.Error
if errors.As(err, &networkErr) && networkErr.Timeout() {
return model.Attachment{}, ErrUploadReadTimeout
}
return model.Attachment{}, err
}
if size > int64(s.maxBytes) {
return model.Attachment{}, ErrInvalidSize
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return model.Attachment{}, err
}
detectedType, width, height, err := s.checkImage(ctx, tmp, contentType)
if err != nil {
return model.Attachment{}, err
}
id, err := uuid.NewV7()
if err != nil {
return model.Attachment{}, err
}
jobID, err := uuid.NewV7()
if err != nil {
return model.Attachment{}, err
}
hash := hex.EncodeToString(hasher.Sum(nil))
key := "chats/" + chatID.String() + "/attachments/" + id.String()
stagingKey := "staging/" + id.String()
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return model.Attachment{}, err
}
if err := s.s3.Put(ctx, stagingKey, tmp, size, string(detectedType)); err != nil {
return model.Attachment{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Attachment{}, err
}
defer tx.Rollback(ctx)
q := s.withTx(tx)
row, err := q.CreateAttachment(ctx, db.CreateAttachmentParams{
ID: id,
ChatID: chatID,
OwnerID: userID,
S3Key: key,
StagingKey: stagingKey,
JobID: jobID,
Filename: filename,
ContentType: db.AttachmentContentType(detectedType),
SizeBytes: int(size),
Sha256: hash,
Width: width,
Height: height,
ErrorCode: "",
})
if postgres.IsNotFound(err) {
return model.Attachment{}, ErrAttachmentNotFound
}
if err != nil {
return model.Attachment{}, err
}
traceparent, tracestate := telemetry.Inject(ctx)
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
AttachmentID: id,
Attempt: 1,
AvailableAt: row.CreatedAt,
Traceparent: traceparent,
Tracestate: tracestate,
}); err != nil {
return model.Attachment{}, err
}
if err := tx.Commit(ctx); err != nil {
return model.Attachment{}, err
}
return model.Attachment{
ID: row.ID,
ChatID: row.ChatID,
OwnerID: row.OwnerID,
Filename: row.Filename,
ContentType: model.ContentType(row.ContentType),
SizeBytes: row.SizeBytes,
Sha256: row.Sha256,
Status: model.AttachmentStatus(row.Status),
Width: row.Width,
Height: row.Height,
ErrorCode: row.ErrorCode,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}, nil
}
func (s *AttachmentService) Get(
ctx context.Context,
userID, attachmentID uuid.UUID,
) (model.Attachment, error) {
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
if postgres.IsNotFound(err) {
return model.Attachment{}, ErrAttachmentNotFound
}
if err != nil {
return model.Attachment{}, err
}
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
return model.Attachment{}, err
}
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
if err != nil {
return model.Attachment{}, err
}
variants := make([]model.AttachmentVariant, 0, len(rows))
for _, v := range rows {
variants = append(variants, model.AttachmentVariant{
Name: model.AttachmentVariantName(v.Variant),
ContentType: model.ContentType(v.ContentType),
SizeBytes: v.SizeBytes,
Width: v.Width,
Height: v.Height,
Sha256: v.Sha256,
})
}
return model.Attachment{
Variants: variants,
ID: row.ID,
ChatID: row.ChatID,
OwnerID: row.OwnerID,
Filename: row.Filename,
ContentType: model.ContentType(row.ContentType),
SizeBytes: row.SizeBytes,
Sha256: row.Sha256,
Status: model.AttachmentStatus(row.Status),
Width: row.Width,
Height: row.Height,
ErrorCode: row.ErrorCode,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}, nil
}
func (s *AttachmentService) GetContent(
ctx context.Context,
userID, attachmentID uuid.UUID,
variant string,
) ([]byte, model.ContentType, error) {
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
if postgres.IsNotFound(err) {
return nil, "", ErrAttachmentNotFound
}
if err != nil {
return nil, "", err
}
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
return nil, "", err
}
if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady {
return nil, "", ErrAttachmentNotReady
}
key, contentType := row.S3Key, model.ContentType(row.ContentType)
if variant != "" && variant != model.AttachmentContentOriginal {
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
if err != nil {
return nil, "", err
}
found := false
for _, v := range rows {
if string(v.Variant) == variant {
key, contentType, found = v.S3Key, model.ContentType(v.ContentType), true
break
}
}
if !found {
return nil, "", ErrAttachmentNotFound
}
}
out, err := s.s3.Get(ctx, key)
if err != nil {
return nil, "", err
}
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
if err != nil {
return nil, "", err
}
return data, contentType, nil
}
func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, int, int, error) {
cfg, format, err := image.DecodeConfig(r)
if err != nil {
return "", 0, 0, ErrInvalidImage
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return "", 0, 0, ErrInvalidImage
}
if cfg.Width > s.maxPixels/cfg.Height {
return "", 0, 0, ErrInvalidSize
}
var detectedType model.ContentType
switch format {
case "png":
if contentType != string(model.ContentTypePNG) {
return "", 0, 0, ErrInvalidImage
}
detectedType = model.ContentTypePNG
case "jpeg":
if contentType != string(model.ContentTypeJPEG) {
return "", 0, 0, ErrInvalidImage
}
detectedType = model.ContentTypeJPEG
default:
return "", 0, 0, ErrInvalidImage
}
select {
case s.decodeSlot <- struct{}{}:
defer func() { <-s.decodeSlot }()
case <-ctx.Done():
return "", 0, 0, ctx.Err()
}
if err := ctx.Err(); err != nil {
return "", 0, 0, err
}
if _, err := r.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, err
}
if _, _, err := image.Decode(r); err != nil {
return "", 0, 0, ErrInvalidImage
}
return detectedType, cfg.Width, cfg.Height, nil
}
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error {
member, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return err
}
if !member {
return ErrAttachmentNotFound
}
return nil
}
+197
View File
@@ -0,0 +1,197 @@
package service
import (
"context"
"errors"
"log/slog"
"time"
"gavrilenko-sxdees/lab7/internal/credentials"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/postgres"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
)
const sessionCacheTTL = 60 * time.Second
const cacheOpTimeout = 300 * time.Millisecond
var (
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUnauthorized = errors.New("unauthorized")
ErrSessionCacheUnavailable = errors.New("session cache unavailable")
)
type authQueries interface {
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error)
GetUserByUsername(ctx context.Context, username string) (db.User, error)
UpdatePasswordHash(ctx context.Context, arg db.UpdatePasswordHashParams) error
}
type AuthService struct {
q authQueries
cache *goredis.Client
sessionTTL time.Duration
log *slog.Logger
}
func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService {
return &AuthService{
q: q,
cache: cache,
sessionTTL: sessionTTL,
log: log,
}
}
func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) {
user, err := s.q.GetUserByUsername(ctx, username)
if postgres.IsNotFound(err) {
credentials.DummyVerify(plain)
return model.Session{}, ErrInvalidCredentials
}
if err != nil {
return model.Session{}, err
}
if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil {
if errors.Is(err, credentials.ErrPasswordMismatch) {
return model.Session{}, ErrInvalidCredentials
}
return model.Session{}, err
}
if credentials.NeedsRehash(user.PasswordHash) {
newHash, herr := credentials.HashPassword(plain)
if herr == nil {
_ = s.q.UpdatePasswordHash(ctx, db.UpdatePasswordHashParams{
PasswordHash: newHash,
ID: user.ID,
})
}
}
token := credentials.NewToken()
expiresAt := time.Now().UTC().Add(s.sessionTTL)
err = s.q.CreateSession(ctx, db.CreateSessionParams{
TokenHash: credentials.HashToken(token),
UserID: user.ID,
ExpiresAt: expiresAt,
})
if err != nil {
return model.Session{}, err
}
return model.Session{
Token: token,
ExpiresAt: expiresAt,
User: model.User{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: user.CreatedAt.UTC(),
},
}, nil
}
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
tokenHash := credentials.HashToken(token)
key := cacheKey(tokenHash)
if id, ok := s.cacheGet(ctx, key); ok {
return id, nil
}
row, err := s.q.GetActiveSession(ctx, tokenHash)
if postgres.IsNotFound(err) {
return uuid.Nil, ErrUnauthorized
}
if err != nil {
return uuid.Nil, err
}
s.cacheSet(ctx, key, row.UserID, min(time.Until(row.ExpiresAt), sessionCacheTTL))
return row.UserID, nil
}
func (s *AuthService) Logout(ctx context.Context, token string) error {
tokenHash := credentials.HashToken(token)
n, err := s.q.DeleteSession(ctx, tokenHash)
if err != nil {
return err
}
if err := s.cacheDel(ctx, cacheKey(tokenHash)); err != nil {
return ErrSessionCacheUnavailable
}
if n == 0 {
return ErrUnauthorized
}
return nil
}
func cacheKey(tokenHash string) string {
return "session:" + tokenHash
}
func (s *AuthService) cacheGet(ctx context.Context, key string) (uuid.UUID, bool) {
if s.cache == nil {
return uuid.Nil, false
}
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
defer cancel()
val, err := s.cache.Get(cctx, key).Result()
switch {
case err == nil:
id, perr := uuid.Parse(val)
if perr != nil {
s.log.Warn("session cache value is not a uuid", "error", perr)
return uuid.Nil, false
}
s.log.Debug("session cache hit")
return id, true
case errors.Is(err, goredis.Nil):
s.log.Debug("session cache miss")
default:
s.log.Warn("session cache get failed, falling back to database", "error", err)
}
return uuid.Nil, false
}
func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, ttl time.Duration) {
if s.cache == nil || ttl <= 0 {
return
}
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
defer cancel()
if err := s.cache.Set(cctx, key, id.String(), ttl).Err(); err != nil {
s.log.Warn("session cache set failed", "error", err)
}
}
func (s *AuthService) cacheDel(ctx context.Context, key string) error {
if s.cache == nil {
return nil
}
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
defer cancel()
if err := s.cache.Del(cctx, key).Err(); err != nil {
s.log.Warn("session cache delete failed", "error", err)
return err
}
return nil
}
+204
View File
@@ -0,0 +1,204 @@
package service
import (
"bytes"
"context"
"errors"
"slices"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/postgres"
)
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 chatQueries interface {
AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error)
ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error)
ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error)
}
type ChatService struct {
pool txBeginner
q chatQueries
withTx func(pgx.Tx) chatQueries
}
func NewChatService(pool *pgxpool.Pool, q *db.Queries) *ChatService {
return &ChatService{
pool: pool,
q: q,
withTx: func(tx pgx.Tx) chatQueries {
return q.WithTx(tx)
},
}
}
func (s *ChatService) Create(
ctx context.Context,
userID uuid.UUID,
title string,
memberIDs []uuid.UUID,
) (model.Chat, error) {
if !slices.Contains(memberIDs, userID) {
return model.Chat{}, ErrNotChatMember
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, err
}
defer tx.Rollback(ctx)
q := s.withTx(tx)
id, err := uuid.NewV7()
if err != nil {
return model.Chat{}, err
}
row, err := q.CreateChat(ctx, db.CreateChatParams{
ID: id,
Title: title,
})
if err != nil {
return model.Chat{}, err
}
err = q.AddChatMembers(ctx, db.AddChatMembersParams{
ChatID: row.ID,
UserIds: memberIDs,
})
switch postgres.ErrCode(err) {
case postgres.CodeUniqueViolation:
return model.Chat{}, ErrDuplicateMember
case postgres.CodeForeignKeyViolation:
return model.Chat{}, ErrUnknownMember
}
if err != nil {
return model.Chat{}, err
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, err
}
ids := slices.Clone(memberIDs)
slices.SortFunc(ids, func(a, b uuid.UUID) int {
return bytes.Compare(a[:], b[:])
})
return model.Chat{
ID: row.ID,
Title: row.Title,
CreatedAt: row.CreatedAt,
MemberIDs: ids,
}, nil
}
func (s *ChatService) Get(
ctx context.Context,
userID uuid.UUID,
chatID uuid.UUID,
) (model.Chat, error) {
row, err := s.q.GetChat(ctx, db.GetChatParams{
ID: chatID,
UserID: userID,
})
if postgres.IsNotFound(err) {
return model.Chat{}, ErrChatNotFound
}
if err != nil {
return model.Chat{}, err
}
return model.Chat{
ID: row.ID,
Title: row.Title,
CreatedAt: row.CreatedAt,
MemberIDs: row.MemberIds,
}, nil
}
func (s *ChatService) List(
ctx context.Context,
userID uuid.UUID,
limit int,
cursor *string,
) ([]model.Chat, *string, error) {
var chats []model.Chat
if cursor == nil {
rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{
UserID: userID,
Lim: limit + 1,
})
if err != nil {
return nil, nil, err
}
chats = make([]model.Chat, 0, len(rows))
for _, r := range rows {
chats = append(chats, model.Chat{
ID: r.ID,
Title: r.Title,
CreatedAt: r.CreatedAt,
MemberIDs: r.MemberIds,
})
}
} else {
decoded, derr := decodeCursor(*cursor, uuid.Nil)
if derr != nil {
return nil, nil, ErrInvalidCursor
}
rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{
UserID: userID,
AfterCreatedAt: decoded.CreatedAt,
AfterID: decoded.ID,
Lim: limit + 1,
})
if err != nil {
return nil, nil, err
}
chats = make([]model.Chat, 0, len(rows))
for _, r := range rows {
chats = append(chats, model.Chat{
ID: r.ID,
Title: r.Title,
CreatedAt: r.CreatedAt,
MemberIDs: r.MemberIds,
})
}
}
hasMore := len(chats) > limit
if hasMore {
chats = chats[:limit]
}
var next *string
if hasMore {
last := chats[len(chats)-1]
c := encodeCursor(Cursor{
CreatedAt: last.CreatedAt,
ID: last.ID,
})
next = &c
}
return chats, next, nil
}
+41
View File
@@ -0,0 +1,41 @@
package service
import (
"encoding/base64"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
)
var ErrInvalidCursor = errors.New("invalid cursor")
type Cursor struct {
ChatID uuid.UUID `json:"chat_id"`
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, chatID uuid.UUID) (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() || cursor.ChatID != chatID {
return Cursor{}, ErrInvalidCursor
}
return cursor, nil
}
+289
View File
@@ -0,0 +1,289 @@
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"sort"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/postgres"
)
var (
ErrMessageChatNotFound = errors.New("chat not found")
ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request")
)
type messageQueries interface {
CreateIdempotencyKey(ctx context.Context, arg db.CreateIdempotencyKeyParams) (int64, error)
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
CreateMessageAttachment(ctx context.Context, arg db.CreateMessageAttachmentParams) error
GetIdempotentMessage(ctx context.Context, arg db.GetIdempotentMessageParams) (db.GetIdempotentMessageRow, error)
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
ListAttachmentsByIDs(ctx context.Context, arg db.ListAttachmentsByIDsParams) ([]db.AttachmentStatus, error)
ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error)
ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIDs []uuid.UUID) ([]db.ListMessageAttachmentsByMessageIDsRow, error)
ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error)
ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error)
}
type MessageService struct {
pool txBeginner
q *db.Queries
withTx func(pgx.Tx) messageQueries
}
func NewMessageService(pool *pgxpool.Pool, q *db.Queries) *MessageService {
return &MessageService{
pool: pool,
q: q,
withTx: func(tx pgx.Tx) messageQueries {
return q.WithTx(tx)
},
}
}
func (s *MessageService) Create(
ctx context.Context,
userID uuid.UUID,
chatID uuid.UUID,
key string,
text string,
attachmentIDs []uuid.UUID,
) (model.Message, error) {
id, err := uuid.NewV7()
if err != nil {
return model.Message{}, err
}
if len(attachmentIDs) > 0 {
statuses, err := s.q.ListAttachmentsByIDs(ctx, db.ListAttachmentsByIDsParams{
ChatID: chatID,
Ids: attachmentIDs,
})
if err != nil {
return model.Message{}, err
}
if len(statuses) != len(attachmentIDs) {
return model.Message{}, ErrAttachmentNotFound
}
for _, status := range statuses {
if status == db.AttachmentStatusFailed {
return model.Message{}, ErrAttachmentNotReady
}
}
}
hashInput := text + "|" + normalizeAttachmentIDs(attachmentIDs)
sum := sha256.Sum256([]byte(hashInput))
hash := hex.EncodeToString(sum[:])
path := "/api/v1/chats/" + chatID.String() + "/messages"
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, err
}
defer tx.Rollback(ctx)
q := s.withTx(tx)
inserted, err := q.CreateIdempotencyKey(ctx, db.CreateIdempotencyKeyParams{
UserID: userID,
Method: http.MethodPost,
Path: path,
Key: key,
RequestHash: hash,
MessageID: id,
})
if err != nil {
return model.Message{}, err
}
if inserted == 0 {
isMember, err := q.IsChatMember(ctx, db.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return model.Message{}, err
}
if !isMember {
return model.Message{}, ErrMessageChatNotFound
}
stored, err := q.GetIdempotentMessage(ctx, db.GetIdempotentMessageParams{
UserID: userID,
Method: http.MethodPost,
Path: path,
Key: key,
})
if err != nil {
return model.Message{}, err
}
if stored.RequestHash != hash {
return model.Message{}, ErrIdempotencyKeyConflict
}
storedAttachmentIDs, err := q.ListMessageAttachmentIDs(ctx, stored.ID)
if err != nil {
return model.Message{}, err
}
return model.Message{
ID: stored.ID,
ChatID: stored.ChatID,
SenderID: stored.SenderID,
Text: stored.Text,
AttachmentIDs: storedAttachmentIDs,
CreatedAt: stored.CreatedAt,
}, nil
}
row, err := q.CreateMessage(ctx, db.CreateMessageParams{
ID: id,
ChatID: chatID,
SenderID: userID,
Text: text,
})
if postgres.IsNotFound(err) {
return model.Message{}, ErrMessageChatNotFound
}
if err != nil {
return model.Message{}, err
}
for i, attachmentID := range attachmentIDs {
if err := q.CreateMessageAttachment(ctx, db.CreateMessageAttachmentParams{
MessageID: id,
AttachmentID: attachmentID,
Position: i,
}); err != nil {
return model.Message{}, err
}
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, err
}
return model.Message{
ID: row.ID,
ChatID: row.ChatID,
SenderID: row.SenderID,
Text: row.Text,
AttachmentIDs: attachmentIDs,
CreatedAt: row.CreatedAt,
}, nil
}
func (s *MessageService) List(
ctx context.Context,
userID uuid.UUID,
chatID uuid.UUID,
limit int,
cursor *string,
) ([]model.Message, *string, error) {
isMember, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return nil, nil, err
}
if !isMember {
return nil, nil, ErrMessageChatNotFound
}
var rows []db.Message
if cursor == nil {
rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{
ChatID: chatID,
Lim: limit + 1,
})
} else {
decoded, derr := decodeCursor(*cursor, chatID)
if derr != nil {
return nil, nil, ErrInvalidCursor
}
rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{
ChatID: chatID,
AfterCreatedAt: decoded.CreatedAt,
AfterID: decoded.ID,
Lim: limit + 1,
})
}
if err != nil {
return nil, nil, err
}
hasMore := len(rows) > limit
if hasMore {
rows = rows[:limit]
}
attachmentsByMessage := make(map[uuid.UUID][]uuid.UUID, len(rows))
if len(rows) > 0 {
messageIDs := make([]uuid.UUID, len(rows))
for i, r := range rows {
messageIDs[i] = r.ID
}
links, err := s.q.ListMessageAttachmentsByMessageIDs(ctx, messageIDs)
if err != nil {
return nil, nil, err
}
for _, l := range links {
attachmentsByMessage[l.MessageID] = append(attachmentsByMessage[l.MessageID], l.AttachmentID)
}
}
messages := make([]model.Message, 0, len(rows))
for _, r := range rows {
messages = append(messages, model.Message{
ID: r.ID,
ChatID: r.ChatID,
SenderID: r.SenderID,
Text: r.Text,
AttachmentIDs: attachmentsByMessage[r.ID],
CreatedAt: r.CreatedAt,
})
}
var next *string
if hasMore {
last := messages[len(messages)-1]
c := encodeCursor(Cursor{
ChatID: chatID,
CreatedAt: last.CreatedAt,
ID: last.ID,
})
next = &c
}
return messages, next, nil
}
func normalizeAttachmentIDs(ids []uuid.UUID) string {
if len(ids) == 0 {
return ""
}
parts := make([]string, len(ids))
for i, id := range ids {
parts[i] = id.String()
}
sort.Strings(parts)
return strings.Join(parts, ",")
}
+11
View File
@@ -0,0 +1,11 @@
package service
import (
"context"
"github.com/jackc/pgx/v5"
)
type txBeginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
}
+83
View File
@@ -0,0 +1,83 @@
package service
import (
"context"
"errors"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/credentials"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/postgres"
)
var (
ErrUsernameTaken = errors.New("username already taken")
ErrUserNotFound = errors.New("user not found")
)
type userQueries interface {
CreateUser(ctx context.Context, arg db.CreateUserParams) (db.CreateUserRow, error)
GetUser(ctx context.Context, id uuid.UUID) (db.GetUserRow, error)
}
type UserService struct {
q userQueries
}
func NewUserService(q userQueries) *UserService {
return &UserService{q: q}
}
func (s *UserService) Create(
ctx context.Context,
username, displayName, plain string,
) (model.User, error) {
hash, err := credentials.HashPassword(plain)
if err != nil {
return model.User{}, err
}
id, err := uuid.NewV7()
if err != nil {
return model.User{}, err
}
row, err := s.q.CreateUser(ctx, db.CreateUserParams{
ID: id,
Username: username,
DisplayName: displayName,
PasswordHash: hash,
})
if err != nil {
if postgres.ErrCode(err) == postgres.CodeUniqueViolation {
return model.User{}, ErrUsernameTaken
}
return model.User{}, err
}
return model.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: row.CreatedAt.UTC(),
}, nil
}
func (s *UserService) GetByID(ctx context.Context, id uuid.UUID) (model.User, error) {
row, err := s.q.GetUser(ctx, id)
if postgres.IsNotFound(err) {
return model.User{}, ErrUserNotFound
}
if err != nil {
return model.User{}, err
}
return model.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: row.CreatedAt.UTC(),
}, nil
}
+41
View File
@@ -0,0 +1,41 @@
package telemetry
import (
"context"
"net/http"
"github.com/go-chi/chi/v5"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
func Incoming(r *http.Request) context.Context {
return otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
}
type roundTripper struct{ next http.RoundTripper }
func Transport(next http.RoundTripper) http.RoundTripper {
if next == nil {
next = http.DefaultTransport
}
return &roundTripper{next: next}
}
func (t *roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
ctx, span := Start(r.Context(), "s3.request", trace.SpanKindClient)
defer span.End()
resp, err := t.next.RoundTrip(r.Clone(ctx))
Failure(span, err)
return resp, err
}
func RoutePattern(r *http.Request) string {
if rc := chi.RouteContext(r.Context()); rc != nil {
if pattern := rc.RoutePattern(); pattern != "" {
return pattern
}
}
return r.URL.Path
}
+329
View File
@@ -0,0 +1,329 @@
// Package telemetry exports OTLP metrics, logs and traces without affecting business readiness.
package telemetry
import (
"context"
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/contrib/bridges/otelslog"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.32.0"
"go.opentelemetry.io/otel/trace"
)
const version = "7.0.0-lab"
var (
httpRequests metric.Int64Counter
httpDuration metric.Float64Histogram
jobsCount metric.Int64Counter
jobDuration metric.Float64Histogram
readyHist metric.Float64Histogram
pendingAcquires atomic.Int64
busyWorkers atomic.Int64
workerCapacity atomic.Int64
tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
)
func Init(ctx context.Context, service string) (*slog.Logger, func(), error) {
host, _ := os.Hostname()
res := resource.NewWithAttributes(
semconv.SchemaURL,
attribute.String("service.name", service),
attribute.String("service.version", version),
attribute.String("service.instance.id", host),
attribute.String("deployment.environment.name", "lab"),
)
otel.SetTextMapPropagator(propagation.TraceContext{})
std := slog.NewJSONHandler(os.Stdout, nil)
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
return slog.New(&contextHandler{next: std, service: service}), func() {}, nil
}
traceOpts := []otlptracehttp.Option{otlptracehttp.WithTimeout(time.Second)}
traceExp, err := otlptracehttp.New(ctx, traceOpts...)
if err != nil {
return nil, nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))),
sdktrace.WithBatcher(traceExp,
sdktrace.WithMaxQueueSize(1024),
sdktrace.WithMaxExportBatchSize(128),
sdktrace.WithBatchTimeout(time.Second),
sdktrace.WithExportTimeout(time.Second),
),
)
otel.SetTracerProvider(tp)
tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
metricOpts := []otlpmetrichttp.Option{otlpmetrichttp.WithTimeout(time.Second)}
metricExp, err := otlpmetrichttp.New(ctx, metricOpts...)
if err != nil {
return nil, nil, err
}
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120}
mp := sdkmetric.NewMeterProvider(
sdkmetric.WithResource(res),
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp,
sdkmetric.WithInterval(2*time.Second),
sdkmetric.WithTimeout(time.Second),
)),
sdkmetric.WithView(sdkmetric.NewView(
sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: buckets}},
)),
)
otel.SetMeterProvider(mp)
logOpts := []otlploghttp.Option{otlploghttp.WithTimeout(time.Second)}
logExp, err := otlploghttp.New(ctx, logOpts...)
if err != nil {
return nil, nil, err
}
lp := sdklog.NewLoggerProvider(
sdklog.WithResource(res),
sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp,
sdklog.WithMaxQueueSize(1024),
sdklog.WithExportMaxBatchSize(128),
sdklog.WithExportInterval(time.Second),
sdklog.WithExportTimeout(time.Second),
)),
)
logHandler := slog.New(&contextHandler{
next: &tee{
a: std,
b: otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp)),
},
service: service,
})
m := otel.Meter("messenger")
httpRequests, _ = m.Int64Counter("http.server.requests")
httpDuration, _ = m.Float64Histogram("http.server.duration", metric.WithUnit("s"))
jobsCount, _ = m.Int64Counter("messenger.jobs")
jobDuration, _ = m.Float64Histogram("messenger.job.duration", metric.WithUnit("s"))
readyHist, _ = m.Float64Histogram("messenger.attachment.ready.duration", metric.WithUnit("s"))
shutdown := func() {
c, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
_ = tp.Shutdown(c)
_ = mp.Shutdown(c)
_ = lp.Shutdown(c)
}
return logHandler, shutdown, nil
}
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
return tracer.Start(ctx, name, trace.WithSpanKind(kind))
}
func Failure(span trace.Span, err error) {
if err != nil {
span.SetStatus(codes.Error, "operation failed")
}
}
func Inject(ctx context.Context) (string, string) {
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
return carrier.Get("traceparent"), carrier.Get("tracestate")
}
func Extract(ctx context.Context, parent, state string) context.Context {
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{
"traceparent": parent,
"tracestate": state,
})
}
func TraceID(ctx context.Context) string {
return trace.SpanContextFromContext(ctx).TraceID().String()
}
func HTTP(ctx context.Context, method, route string, status int, seconds float64) {
switch method {
case "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS":
default:
method = "_OTHER"
}
if httpRequests == nil {
return
}
attrs := metric.WithAttributes(
attribute.String("method", method),
attribute.String("route", route),
attribute.String("status_class", fmt.Sprintf("%dxx", status/100)),
)
httpRequests.Add(ctx, 1, attrs)
httpDuration.Record(ctx, seconds, attrs)
}
func Job(ctx context.Context, outcome string, seconds float64) {
if jobsCount == nil {
return
}
attrs := metric.WithAttributes(
attribute.String("job_type", "attachment.process.v1"),
attribute.String("outcome", outcome),
)
jobsCount.Add(ctx, 1, attrs)
jobDuration.Record(ctx, seconds, attrs)
}
func Ready(ctx context.Context, seconds float64) {
if readyHist != nil {
readyHist.Record(ctx, seconds)
}
}
func SetWorkerCapacity(n int) {
workerCapacity.Store(int64(n))
}
func IncBusy() { busyWorkers.Add(1) }
func DecBusy() { busyWorkers.Add(-1) }
func IncWait() { pendingAcquires.Add(1) }
func DecWait() { pendingAcquires.Add(-1) }
func RegisterPoolObservers(pool *pgxpool.Pool, workerRole bool) {
m := otel.Meter("messenger")
poolUsed, _ := m.Int64ObservableGauge("messenger.db.pool.used")
poolLimit, _ := m.Int64ObservableGauge("messenger.db.pool.limit")
poolWaiting, _ := m.Int64ObservableGauge("messenger.db.pool.waiting")
queueDepth, _ := m.Int64ObservableGauge("messenger.queue.depth")
queueAge, _ := m.Float64ObservableGauge("messenger.queue.oldest_age_seconds", metric.WithUnit("s"))
busy, _ := m.Int64ObservableGauge("messenger.worker.busy")
capacity, _ := m.Int64ObservableGauge("messenger.worker.capacity")
sliTotal, _ := m.Int64ObservableCounter("messenger.attachment.sli.total")
sliBad, _ := m.Int64ObservableCounter("messenger.attachment.sli.bad")
_, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
stat := pool.Stat()
o.ObserveInt64(poolUsed, int64(stat.AcquiredConns()))
o.ObserveInt64(poolLimit, int64(stat.MaxConns()))
o.ObserveInt64(poolWaiting, pendingAcquires.Load())
if workerRole {
o.ObserveInt64(busy, busyWorkers.Load())
o.ObserveInt64(capacity, workerCapacity.Load())
qctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
var depth int64
var oldest float64
err := pool.QueryRow(qctx, `
SELECT count(*),
COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8
FROM attachments
WHERE status IN ('queued', 'processing')`).Scan(&depth, &oldest)
if err == nil {
o.ObserveInt64(queueDepth, depth)
o.ObserveFloat64(queueAge, oldest)
}
var matured, bad int64
err = pool.QueryRow(qctx, `
SELECT count(*),
count(*) FILTER (
WHERE status = 'failed'
OR (status = 'ready' AND updated_at > created_at + interval '5 seconds')
)
FROM attachments
WHERE created_at <= clock_timestamp() - interval '5 seconds'
AND status IN ('ready', 'failed')`).Scan(&matured, &bad)
if err == nil {
o.ObserveInt64(sliTotal, matured)
o.ObserveInt64(sliBad, bad)
}
}
return nil
}, poolUsed, poolLimit, poolWaiting, queueDepth, queueAge, busy, capacity, sliTotal, sliBad)
}
type contextHandler struct {
next slog.Handler
service string
}
func (h *contextHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.next.Enabled(ctx, level)
}
func (h *contextHandler) Handle(ctx context.Context, r slog.Record) error {
r.AddAttrs(
slog.String("service.name", h.service),
slog.String("event", r.Message),
)
sc := trace.SpanContextFromContext(ctx)
if sc.IsValid() {
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
)
}
return h.next.Handle(ctx, r)
}
func (h *contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &contextHandler{next: h.next.WithAttrs(attrs), service: h.service}
}
func (h *contextHandler) WithGroup(name string) slog.Handler {
return &contextHandler{next: h.next.WithGroup(name), service: h.service}
}
type tee struct{ a, b slog.Handler }
func (t *tee) Enabled(ctx context.Context, level slog.Level) bool {
return t.a.Enabled(ctx, level) || t.b.Enabled(ctx, level)
}
func (t *tee) Handle(ctx context.Context, r slog.Record) error {
_ = t.a.Handle(ctx, r.Clone())
return t.b.Handle(ctx, r)
}
func (t *tee) WithAttrs(attrs []slog.Attr) slog.Handler {
return &tee{t.a.WithAttrs(attrs), t.b.WithAttrs(attrs)}
}
func (t *tee) WithGroup(name string) slog.Handler {
return &tee{t.a.WithGroup(name), t.b.WithGroup(name)}
}
func ProcessRSS() int64 {
raw, err := os.ReadFile("/proc/self/stat")
if err != nil {
return 0
}
end := strings.LastIndex(string(raw), ")")
if end < 0 {
return 0
}
fields := strings.Fields(string(raw)[end+1:])
if len(fields) < 22 {
return 0
}
pages, _ := strconv.ParseInt(fields[21], 10, 64)
return pages * int64(os.Getpagesize())
}
+71
View File
@@ -0,0 +1,71 @@
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
// ClientTLSFromFiles loads a client TLS config for outbound mTLS.
func ClientTLSFromFiles(certFile, keyFile, caFile, serverName string) (*tls.Config, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("load client cert: %w", err)
}
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read ca: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, fmt.Errorf("parse ca pem")
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
MinVersion: tls.VersionTLS12,
ServerName: serverName,
}, nil
}
func ClientTLSFromEnv(prefix string) (*tls.Config, error) {
cert := os.Getenv(prefix + "_CLIENT_CERT")
key := os.Getenv(prefix + "_CLIENT_KEY")
ca := os.Getenv(prefix + "_CA_FILE")
server := os.Getenv(prefix + "_SERVER_NAME")
if cert == "" || key == "" || ca == "" {
return nil, nil
}
if server == "" {
server = "broker-gw"
}
cfg, err := ClientTLSFromFiles(cert, key, ca, server)
if err != nil || cfg == nil {
return cfg, err
}
if chainFile := os.Getenv(prefix + "_CHAIN_FILE"); chainFile != "" {
if err := appendChain(cfg, chainFile); err != nil {
return nil, err
}
}
return cfg, nil
}
func appendChain(cfg *tls.Config, chainFile string) error {
if len(cfg.Certificates) == 0 {
return nil
}
pemBytes, err := os.ReadFile(chainFile)
if err != nil {
return fmt.Errorf("read chain: %w", err)
}
for block, rest := pem.Decode(pemBytes); block != nil; block, rest = pem.Decode(rest) {
if block.Type != "CERTIFICATE" {
continue
}
cfg.Certificates[0].Certificate = append(cfg.Certificates[0].Certificate, block.Bytes)
}
return nil
}
+19
View File
@@ -0,0 +1,19 @@
package tlsconfig
import (
"crypto/tls"
"testing"
)
func TestBrokerClientPEMChain(t *testing.T) {
cert, err := tls.LoadX509KeyPair(
"../../secrets/broker-api-client.crt",
"../../secrets/broker-api-client.key",
)
if err != nil {
t.Skip(err)
}
if len(cert.Certificate) < 2 {
t.Fatalf("want chained client cert, got %d DER entries", len(cert.Certificate))
}
}
+90
View File
@@ -0,0 +1,90 @@
package tlslisten
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"
"strings"
)
// LoadServerTLS builds a server tls.Config with mandatory client certificate verification.
func LoadServerTLS(certFile, keyFile, caFile, allowedClientSAN string) (*tls.Config, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("load server cert: %w", err)
}
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read ca: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, fmt.Errorf("parse ca pem")
}
cfg := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: pool,
MinVersion: tls.VersionTLS12,
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return fmt.Errorf("missing client certificate")
}
leaf, err := x509.ParseCertificate(rawCerts[0])
if err != nil {
return err
}
if err := leaf.VerifyHostname(allowedClientSAN); err != nil {
// Also accept if allowed SAN appears in DNSNames.
for _, name := range leaf.DNSNames {
if name == allowedClientSAN {
return nil
}
}
if leaf.Subject.CommonName == allowedClientSAN {
return nil
}
return fmt.Errorf("client identity %q not allowed (want %q)", leaf.Subject.CommonName, allowedClientSAN)
}
return nil
},
}
return cfg, nil
}
func ListenAndServeTLS(server *http.Server, cfg *tls.Config) error {
ln, err := tls.Listen("tcp", server.Addr, cfg)
if err != nil {
return err
}
return server.Serve(ln)
}
// ClientHTTP returns an http.Client that presents the given client certificate and trusts caFile.
func ClientHTTP(certFile, keyFile, caFile string) (*http.Client, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
MinVersion: tls.VersionTLS12,
},
}
return &http.Client{Transport: tr}, nil
}
// TLSEnabled reports whether the process should terminate TLS on the API port.
func TLSEnabled() bool {
return strings.TrimSpace(os.Getenv("TLS_CERT_FILE")) != "" && strings.TrimSpace(os.Getenv("TLS_KEY_FILE")) != ""
}
+225
View File
@@ -0,0 +1,225 @@
package worker
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/color"
"image/draw"
"image/jpeg"
_ "image/png"
"io"
"os"
"strconv"
"github.com/disintegration/imaging"
"github.com/gen2brain/webp"
"gavrilenko-sxdees/lab7/internal/db"
)
var (
ErrInvalidSource = errors.New("invalid source image")
ErrUnsupportedPipelineVersion = errors.New("unsupported pipeline version")
)
type imageVariant struct {
Name db.AttachmentVariantName
Data []byte
ContentType string
Width, Height int
}
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
if row.StagingKey == nil {
return nil, ErrInvalidSource
}
source, err := w.s3.Get(ctx, *row.StagingKey)
if err != nil {
return nil, err
}
defer source.Body.Close()
tmp, err := os.CreateTemp("", "attachment-job-*")
if err != nil {
return nil, err
}
defer func() {
_ = tmp.Close()
_ = os.Remove(tmp.Name())
}()
hash := sha256.New()
size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1))
if err != nil {
return nil, err
}
if size != int64(row.SizeBytes) ||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
return nil, ErrInvalidSource
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return nil, err
}
select {
case w.decodeSlot <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
if err := ctx.Err(); err != nil {
<-w.decodeSlot
return nil, err
}
images, err := runImageProcess(ctx, tmp, w.maxPixels, row.PipelineVersion)
<-w.decodeSlot
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return nil, err
}
if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil {
return nil, err
}
variants := make([]db.CreateAttachmentVariantParams, 0, len(images))
for _, img := range images {
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.Name)
if err := w.s3.Put(ctx, key, bytes.NewReader(img.Data), int64(len(img.Data)), img.ContentType); err != nil {
return nil, err
}
sum := sha256.Sum256(img.Data)
variants = append(variants, db.CreateAttachmentVariantParams{
AttachmentID: row.ID,
PipelineVersion: row.PipelineVersion,
Variant: img.Name,
S3Key: key,
ContentType: img.ContentType,
SizeBytes: len(img.Data),
Width: img.Width,
Height: img.Height,
Sha256: hex.EncodeToString(sum[:]),
})
}
return variants, nil
}
func imageVariants(r io.ReadSeeker, maxPixels, pipelineVersion int) ([]imageVariant, error) {
quality := 80
switch pipelineVersion {
case 1:
case 2:
quality = 75
default:
return nil, ErrUnsupportedPipelineVersion
}
cfg, format, err := image.DecodeConfig(r)
if err != nil ||
(format != "png" && format != "jpeg") ||
cfg.Width <= 0 ||
cfg.Height <= 0 ||
cfg.Width > maxPixels/cfg.Height {
return nil, ErrInvalidSource
}
if _, err := r.Seek(0, io.SeekStart); err != nil {
return nil, err
}
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
if err != nil {
return nil, ErrInvalidSource
}
variants := make([]imageVariant, 0, 3)
for _, item := range []struct {
name db.AttachmentVariantName
image image.Image
}{
{db.AttachmentVariantNameThumbnail, fitImage(src, 256)},
{db.AttachmentVariantNameCrop, imaging.Fill(src, 128, 128, imaging.Center, imaging.Lanczos)},
{db.AttachmentVariantNameOptimized, fitImage(src, 1280)},
} {
var data []byte
contentType := "image/jpeg"
if item.name == db.AttachmentVariantNameOptimized {
contentType = "image/webp"
data, err = encodeWebP(item.image, quality)
} else {
data, err = encodeJPEG(item.image, 85)
}
if err != nil {
return nil, err
}
variants = append(variants, imageVariant{
Name: item.name,
ContentType: contentType,
Data: data,
Width: item.image.Bounds().Dx(),
Height: item.image.Bounds().Dy(),
})
}
return variants, nil
}
func fitImage(src image.Image, maxSize int) image.Image {
width, height := src.Bounds().Dx(), src.Bounds().Dy()
if width > maxSize || height > maxSize {
if width >= height {
height = max(1, height*maxSize/width)
width = maxSize
} else {
width = max(1, width*maxSize/height)
height = maxSize
}
return imaging.Resize(src, width, height, imaging.Lanczos)
}
return src
}
func encodeJPEG(src image.Image, quality int) ([]byte, error) {
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx(), src.Bounds().Dy()))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
var out bytes.Buffer
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func encodeWebP(src image.Image, quality int) ([]byte, error) {
var out bytes.Buffer
if err := webp.Encode(&out, src, webp.Options{Quality: quality, Method: 4}); err != nil {
return nil, err
}
return out.Bytes(), nil
}
+53
View File
@@ -0,0 +1,53 @@
package worker
import (
"bytes"
"context"
"encoding/gob"
"errors"
"os"
"os/exec"
"strconv"
)
func ProcessImage(maxPixels, pipelineVersion int) error {
variants, err := imageVariants(os.Stdin, maxPixels, pipelineVersion)
if err != nil {
return err
}
return gob.NewEncoder(os.Stdout).Encode(variants)
}
func runImageProcess(ctx context.Context, source *os.File, maxPixels, pipelineVersion int) ([]imageVariant, error) {
executable, err := os.Executable()
if err != nil {
return nil, err
}
cmd := exec.CommandContext(ctx, executable,
"-process-image", strconv.Itoa(maxPixels),
"-pipeline-version", strconv.Itoa(pipelineVersion),
)
cmd.Stdin = source
data, err := cmd.Output()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {
return nil, ErrInvalidSource
}
return nil, err
}
var variants []imageVariant
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&variants); err != nil {
return nil, err
}
return variants, nil
}
+226
View File
@@ -0,0 +1,226 @@
package worker
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"time"
"github.com/jackc/pgx/v5"
"go.opentelemetry.io/otel/trace"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
s3store "gavrilenko-sxdees/lab7/internal/s3"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
var (
errLeaseExpired = errors.New("attachment lease expired")
errMissingThumbnail = errors.New("ready attachment has no thumbnail")
errAttemptProcessing = errors.New("attachment attempt is still processing")
errAttemptUnavailable = errors.New("attachment attempt is not yet available")
errEffectChecksumMismatch = errors.New("attachment effect checksum mismatch")
)
func (w *Worker) handle(ctx context.Context, job model.AttachmentJob) error {
jobCtx, cancel := context.WithTimeout(ctx, w.cfg.Timeout)
defer cancel()
row, err := w.q.ClaimAttachmentJob(jobCtx, db.ClaimAttachmentJobParams{
ID: job.AttachmentID,
JobID: job.JobID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
LeaseUntil: time.Now().Add(w.cfg.Timeout),
})
if errors.Is(err, pgx.ErrNoRows) {
return w.duplicate(jobCtx, job)
}
if err != nil {
return err
}
w.log.Info("attachment processing", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
transformCtx, transformSpan := telemetry.Start(jobCtx, "image.transform", trace.SpanKindInternal)
variants, processErr := w.process(transformCtx, row)
telemetry.Failure(transformSpan, processErr)
transformSpan.End()
if processErr != nil {
resultCtx, resultCancel := context.WithTimeout(ctx, 5*time.Second)
defer resultCancel()
return w.finishFailure(resultCtx, job, processErr)
}
tx, err := w.pool.Begin(jobCtx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
_, err = q.LockAttachmentJob(jobCtx, db.LockAttachmentJobParams{
ID: job.AttachmentID,
JobID: job.JobID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
})
if err != nil {
return err
}
for _, variant := range variants {
if err := q.CreateAttachmentVariant(jobCtx, variant); err != nil {
return err
}
}
n, err := q.CompleteAttachmentJob(jobCtx, db.CompleteAttachmentJobParams{
ID: row.ID,
Attempt: job.Attempt,
})
if err != nil {
return err
}
if n != 1 {
return errLeaseExpired
}
if err := tx.Commit(jobCtx); err != nil {
return err
}
if row.StagingKey != nil {
err := w.deleteStagingObject(ctx, *row.StagingKey)
if err != nil && ctx.Err() == nil {
w.log.Warn("delete ready attachment staging", "attachment_id", row.ID, "error", err)
}
}
telemetry.Ready(jobCtx, time.Since(job.CreatedAt).Seconds())
w.log.Info("attachment ready", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
return nil
}
func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
row, err := w.q.GetAttachmentByID(ctx, job.AttachmentID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if row.JobID == nil || *row.JobID != job.JobID || row.PipelineVersion != job.PipelineVersion {
return nil
}
if row.Status == db.AttachmentStatusFailed {
return nil
}
if row.Status == db.AttachmentStatusReady {
variants, err := w.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{
AttachmentID: row.ID,
PipelineVersion: row.PipelineVersion,
})
if err != nil {
return err
}
if err := verify(ctx, w.s3, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
return err
}
hasThumbnail := false
for _, variant := range variants {
if err := verify(ctx, w.s3, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil {
return err
}
if variant.Variant == db.AttachmentVariantNameThumbnail {
hasThumbnail = true
}
}
if !hasThumbnail {
return errMissingThumbnail
}
return nil
}
if row.Status == db.AttachmentStatusProcessing && row.Attempts == job.Attempt {
return errAttemptProcessing
}
if row.Attempts >= job.Attempt {
return nil
}
return errAttemptUnavailable
}
func verify(ctx context.Context, storage *s3store.Client, key string, size int, checksum string) error {
object, err := storage.Get(ctx, key)
if err != nil {
return err
}
defer object.Body.Close()
hash := sha256.New()
n, err := io.Copy(hash, io.LimitReader(object.Body, int64(size)+1))
if err != nil {
return err
}
if n != int64(size) || hex.EncodeToString(hash.Sum(nil)) != checksum {
return errEffectChecksumMismatch
}
return nil
}
func (w *Worker) deleteStagingObject(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
tx, err := w.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
row, err := q.LockAttachmentByStagingKey(ctx, key)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if row.Status != db.AttachmentStatusReady {
return nil
}
if err := w.s3.Delete(ctx, key); err != nil {
return err
}
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
return err
}
return tx.Commit(ctx)
}
+88
View File
@@ -0,0 +1,88 @@
package worker
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gavrilenko-sxdees/lab7/internal/db"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
var (
errAttachmentNotReplayable = errors.New("attachment is not replayable: expected failed with staging and no existing variants")
errMissingPipelineJob = errors.New("attachment has no pipeline job")
errReplayNotUpdated = errors.New("attachment replay did not update one row")
)
type txBeginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
}
func Replay(
ctx context.Context,
pool txBeginner,
storage *s3store.Client,
id uuid.UUID,
operator, reason string,
) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := db.New(tx)
row, err := q.LockFailedAttachmentForReplay(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return errAttachmentNotReplayable
}
if err != nil {
return err
}
if row.JobID == nil {
return errMissingPipelineJob
}
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
return fmt.Errorf("verify replay source: %w", err)
}
n, err := q.ReplayAttachmentJob(ctx, id)
if err != nil {
return err
}
if n != 1 {
return errReplayNotUpdated
}
if err := q.CreateAttachmentReplay(ctx, db.CreateAttachmentReplayParams{
AttachmentID: id,
Attempt: row.Attempts + 1,
PreviousErrorCode: row.ErrorCode,
Operator: operator,
Reason: reason,
}); err != nil {
return err
}
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
AttachmentID: id,
Attempt: row.Attempts + 1,
AvailableAt: time.Now(),
Traceparent: "",
Tracestate: "",
}); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return err
}
return nil
}
+154
View File
@@ -0,0 +1,154 @@
package worker
import (
"context"
"errors"
"math/rand/v2"
"time"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cause error) error {
tx, err := w.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
row, err := q.LockAttachmentJob(ctx, db.LockAttachmentJobParams{
ID: job.AttachmentID,
JobID: job.JobID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
})
if err != nil {
return err
}
code := "processing_failed"
permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
if permanent {
code = "invalid_source"
} else if errors.Is(cause, context.DeadlineExceeded) {
code = "job_timeout"
}
var n int64
if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
if !permanent {
code = "retry_exhausted"
}
n, err = q.FailAttachmentJob(ctx, db.FailAttachmentJobParams{
ID: row.ID,
Attempt: job.Attempt,
ErrorCode: code,
})
} else {
n, err = q.RetryAttachmentJob(ctx, db.RetryAttachmentJobParams{
ID: row.ID,
Attempt: job.Attempt,
ErrorCode: code,
})
if err == nil && n == 1 {
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
AttachmentID: row.ID,
Attempt: row.Attempts + 1,
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
Traceparent: "",
Tracestate: "",
})
}
}
if err != nil {
return err
}
if n != 1 {
return errLeaseExpired
}
if err := tx.Commit(ctx); err != nil {
return err
}
w.log.Warn(
"attachment processing failed",
"job_id",
job.JobID,
"attempt",
job.Attempt,
"error_code",
code,
)
return nil
}
func (w *Worker) recoverLoop(ctx context.Context) {
for ctx.Err() == nil {
recovered, err := w.recoverOne(ctx)
if err != nil && ctx.Err() == nil {
w.log.Warn("recover attachment lease", "error", err)
}
if (err != nil || !recovered) && !wait(ctx, time.Second) {
return
}
}
}
func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
tx, err := w.pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(context.Background())
q := w.q.WithTx(tx)
rows, err := q.LockExpiredAttachmentJobs(ctx, 1)
if err != nil || len(rows) == 0 {
return false, err
}
row := rows[0]
if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
} else {
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
if err == nil {
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
AttachmentID: row.ID,
Attempt: row.Attempts + 1,
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
Traceparent: "",
Tracestate: "",
})
}
}
if err != nil {
return false, err
}
if err := tx.Commit(ctx); err != nil {
return false, err
}
w.log.Info("attachment lease recovered", "attachment_id", row.ID, "attempt", row.Attempts)
return true, nil
}
func retryDelay(attempt int) time.Duration {
ceiling := time.Second * time.Duration(1<<min(max(attempt, 1), 6))
return ceiling/2 + time.Duration(rand.Int64N(int64(ceiling/2)))
}
+62
View File
@@ -0,0 +1,62 @@
package worker
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gavrilenko-sxdees/lab7/internal/db"
s3store "gavrilenko-sxdees/lab7/internal/s3"
)
var (
errAttachmentNotUpgradeable = errors.New("attachment is not upgradeable: expected v1 queued or processing with staging")
errUpgradeNotUpdated = errors.New("attachment upgrade did not update one row")
)
func Upgrade(ctx context.Context, pool txBeginner, storage *s3store.Client, id uuid.UUID) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
q := db.New(tx)
row, err := q.LockAttachmentForUpgrade(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return errAttachmentNotUpgradeable
}
if err != nil {
return err
}
if row.JobID == nil {
return errMissingPipelineJob
}
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
return err
}
n, err := q.UpgradeAttachmentPipeline(ctx, id)
if err != nil {
return err
}
if n != 1 {
return errUpgradeNotUpdated
}
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
AttachmentID: id,
Attempt: row.Attempts + 1,
AvailableAt: time.Now(),
Traceparent: "",
Tracestate: "",
}); err != nil {
return err
}
return tx.Commit(ctx)
}
+198
View File
@@ -0,0 +1,198 @@
package worker
import (
"context"
"encoding/json"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
amqp "github.com/rabbitmq/amqp091-go"
"go.opentelemetry.io/otel/trace"
"gavrilenko-sxdees/lab7/internal/config"
"gavrilenko-sxdees/lab7/internal/db"
"gavrilenko-sxdees/lab7/internal/model"
"gavrilenko-sxdees/lab7/internal/rabbitmq"
s3store "gavrilenko-sxdees/lab7/internal/s3"
"gavrilenko-sxdees/lab7/internal/telemetry"
)
type Worker struct {
pool *pgxpool.Pool
q *db.Queries
s3 *s3store.Client
brokerURL string
cfg config.WorkerConfig
maxBytes, maxPixels int
decodeSlot chan struct{}
log *slog.Logger
}
func New(
pool *pgxpool.Pool,
s3 *s3store.Client,
brokerURL string,
cfg config.WorkerConfig,
maxBytes, maxPixels int,
log *slog.Logger,
) *Worker {
return &Worker{
pool: pool,
q: db.New(pool),
s3: s3,
brokerURL: brokerURL,
cfg: cfg,
maxBytes: maxBytes,
maxPixels: maxPixels,
decodeSlot: make(chan struct{}, 1),
log: log,
}
}
func (w *Worker) Run(ctx context.Context) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
w.recoverLoop(ctx)
}()
for range w.cfg.Concurrency {
wg.Add(1)
go func() {
defer wg.Done()
w.consumeLoop(ctx)
}()
}
wg.Wait()
}
func (w *Worker) consumeLoop(ctx context.Context) {
for ctx.Err() == nil {
client, err := rabbitmq.New(w.brokerURL)
if err == nil {
err = w.consume(ctx, client)
_ = client.Close()
}
if ctx.Err() != nil {
return
}
w.log.Warn("worker consumer reconnect", "error", err)
if !wait(ctx, 2*time.Second) {
return
}
}
}
func (w *Worker) consume(ctx context.Context, client *rabbitmq.Client) error {
stop := context.AfterFunc(ctx, func() {
_ = client.Close()
})
defer stop()
deliveries, err := client.Consume(ctx, 1)
if err != nil {
return err
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case delivery, ok := <-deliveries:
if !ok {
return amqp.ErrClosed
}
var job model.AttachmentJob
if json.Unmarshal(delivery.Body, &job) != nil ||
job.SchemaVersion != 1 ||
job.Type != "attachment.process.v1" ||
job.JobID == uuid.Nil ||
job.AttachmentID == uuid.Nil ||
(job.PipelineVersion != 1 && job.PipelineVersion != 2) ||
job.Attempt < 1 ||
job.CreatedAt.IsZero() {
if err := delivery.Reject(false); err != nil {
return err
}
w.log.Warn("invalid attachment job rejected")
continue
}
parent, state := job.Traceparent, job.Tracestate
if delivery.Headers != nil {
if v, ok := delivery.Headers["traceparent"].(string); ok && v != "" {
parent = v
}
if v, ok := delivery.Headers["tracestate"].(string); ok && v != "" {
state = v
}
}
jobCtx, span := telemetry.Start(
telemetry.Extract(ctx, parent, state),
"queue.consume",
trace.SpanKindConsumer,
)
telemetry.IncBusy()
started := time.Now()
err := w.handle(jobCtx, job)
telemetry.DecBusy()
outcome := "success"
if err != nil {
outcome = "error"
telemetry.Failure(span, err)
}
telemetry.Job(jobCtx, outcome, time.Since(started).Seconds())
span.End()
if err == nil {
if err := delivery.Ack(false); err != nil {
return err
}
} else {
if ctx.Err() != nil {
return ctx.Err()
}
w.log.Warn(
"attachment job not acknowledged",
"job_id",
job.JobID,
"attempt",
job.Attempt,
"error",
err,
)
if !wait(ctx, time.Second) {
return ctx.Err()
}
if err := delivery.Nack(false, true); err != nil {
return err
}
}
}
}
}
func wait(ctx context.Context, duration time.Duration) bool {
timer := time.NewTimer(duration)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}