Files
mtusi2026lab5/internal/transport/rest/extensions.go
T
Vladislav Kunetskiy 4bdcac3dfa lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
2026-10-30 22:36:52 +03:00

255 lines
6.5 KiB
Go

package rest
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
// SessionResolver is implemented by session.Service. Only token resolution is
// needed here; the generated security handler keeps its own interface.
type SessionResolver interface {
Resolve(ctx context.Context, token string) (domain.User, error)
}
// Extensions implements the optional presigned-upload endpoints. They are
// mounted outside the ogen server so the mandatory OpenAPI contract remains
// untouched.
type Extensions struct {
attachments AttachmentService
sessions SessionResolver
log *slog.Logger
}
func NewExtensions(
attachments AttachmentService,
sessions SessionResolver,
log *slog.Logger,
) *Extensions {
return &Extensions{attachments: attachments, sessions: sessions, log: log}
}
func (e *Extensions) Presign() http.Handler {
return e.route(http.MethodPost, "presign", e.presign)
}
func (e *Extensions) Complete() http.Handler {
return e.route(http.MethodPost, "complete", e.complete)
}
type extensionHandler func(http.ResponseWriter, *http.Request, uuid.UUID) error
func (e *Extensions) route(method, operation string, handler extensionHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
writer := &statusWriter{ResponseWriter: w}
if r.Method != method {
writer.Header().Set("Allow", method)
writeError(r.Context(), e.log, writer, r, http.StatusMethodNotAllowed)
return
}
userID, err := e.authenticate(r)
if err != nil {
e.fail(writer, r, err)
return
}
err = handler(writer, r, userID)
if err != nil {
e.fail(writer, r, err)
return
}
if e.log != nil {
e.log.InfoContext(r.Context(), "extension request handled",
slog.String("request_id", requestIDFromContext(r.Context())),
slog.String("operation", operation),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("user_id", userID.String()),
slog.Int("status", writer.statusCode()),
slog.Duration("duration", time.Since(started)),
)
}
})
}
func (e *Extensions) authenticate(r *http.Request) (uuid.UUID, error) {
header := r.Header.Get("Authorization")
const prefix = "Bearer "
if !strings.HasPrefix(header, prefix) {
return uuid.Nil, fmt.Errorf("%w: bearer token is required", domain.ErrUnauthenticated)
}
token := strings.TrimSpace(strings.TrimPrefix(header, prefix))
if token == "" {
return uuid.Nil, fmt.Errorf("%w: bearer token is empty", domain.ErrUnauthenticated)
}
user, err := e.sessions.Resolve(r.Context(), token)
if err != nil {
// session.Resolve already distinguishes an invalid session (401) from a
// database outage (503); do not collapse both into 401 here.
return uuid.Nil, err
}
return user.ID, nil
}
func (e *Extensions) presign(w http.ResponseWriter, r *http.Request, userID uuid.UUID) error {
chatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
return fmt.Errorf("%w: chat_id is not a UUID", domain.ErrValidation)
}
var request struct {
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
}
if err := decodeJSON(r, &request); err != nil {
return err
}
result, err := e.attachments.Presign(r.Context(), domain.PresignRequest{
ChatID: chatID,
OwnerID: userID,
Filename: request.Filename,
ContentType: request.ContentType,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
})
if err != nil {
return err
}
return writeJSON(w, http.StatusCreated, struct {
AttachmentID string `json:"attachment_id"`
Method string `json:"method"`
UploadURL string `json:"upload_url"`
ExpiresAt time.Time `json:"expires_at"`
SHA256 string `json:"sha256"`
SizeBytes int64 `json:"size_bytes"`
}{
AttachmentID: result.AttachmentID.String(),
Method: http.MethodPut,
UploadURL: result.UploadURL,
ExpiresAt: result.ExpiresAt.UTC(),
SHA256: result.SHA256,
SizeBytes: result.SizeBytes,
})
}
func (e *Extensions) complete(w http.ResponseWriter, r *http.Request, userID uuid.UUID) error {
id, err := uuid.Parse(r.PathValue("attachment_id"))
if err != nil {
return fmt.Errorf("%w: attachment_id is not a UUID", domain.ErrValidation)
}
var request struct {
SHA256 string `json:"sha256"`
}
if err := decodeJSON(r, &request); err != nil {
return err
}
attachment, err := e.attachments.Complete(r.Context(), userID, id, request.SHA256)
if err != nil {
return err
}
return writeJSON(w, http.StatusAccepted, attachmentResponse(attachment))
}
func decodeJSON(r *http.Request, target any) error {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
return fmt.Errorf("%w: Content-Type must be application/json", domain.ErrUnsupportedMedia)
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return fmt.Errorf("%w: decode JSON: %w", domain.ErrValidation, err)
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return fmt.Errorf("%w: trailing JSON data", domain.ErrValidation)
}
return nil
}
func (e *Extensions) fail(w http.ResponseWriter, r *http.Request, err error) {
status := statusForDomainError(err)
if status == http.StatusInternalServerError && e.log != nil {
e.log.ErrorContext(r.Context(), "extension request failed",
slog.String("request_id", requestIDFromContext(r.Context())),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Any("error", err),
)
}
writeError(r.Context(), e.log, w, r, status)
}
func writeJSON(w http.ResponseWriter, status int, payload any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(payload); err != nil {
return fmt.Errorf("write JSON response: %w", err)
}
return nil
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(body []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
return w.ResponseWriter.Write(body)
}
func (w *statusWriter) statusCode() int {
if w.status == 0 {
return http.StatusOK
}
return w.status
}