forked from mtusi2026/mtusi2026lab4
Compare commits
2
Commits
a11463c680
...
8a2d895274
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a2d895274 | ||
|
|
bca081428a |
@@ -116,7 +116,7 @@ docker compose down -v
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
- Nginx, PostgreSQL и SeaweedFS работают в одном экземпляре на одном хосте. Реплики API не защищают от отказа этих компонентов или самого хоста.
|
||||
- При недоступном Redis logout возвращает 204, но прежний токен может приниматься до истечения кэша, до 60 с.
|
||||
- Если удалить сессию из Redis не удалось, logout возвращает `503 unavailable`: сессия уже удалена из PostgreSQL, но старый токен может приниматься из кэша до 60 с. Несмотря на `503`, может потребоваться повторный вход. Пока Redis недоступен, получить `204` нельзя, хотя сессия в БД уже удалена; после восстановления повторный logout вернёт `401`.
|
||||
- Полное декодирование требует памяти под распакованное изображение. Для ограничения расхода RAM на каждой API-реплике работает один декодер, поэтому параллельные загрузки ожидают своей очереди.
|
||||
- Общей транзакции PostgreSQL и S3 нет: расхождения исправляются последующей сверкой. Reconciler отмечает отсутствие оригинала, но не восстанавливает байты. Сохранность volumes не заменяет резервные копии обоих хранилищ.
|
||||
- Фоновая очистка сначала удаляет строку БД, затем объект S3. Если удаление из S3 не удалось, объект останется без метаданных до запуска reconciler.
|
||||
|
||||
@@ -14,6 +14,10 @@ type CreateAttachmentRequest struct {
|
||||
Filename string
|
||||
}
|
||||
|
||||
type GetAttachmentContentRequest struct {
|
||||
Variant string
|
||||
}
|
||||
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
@@ -52,6 +56,10 @@ func (r CreateAttachmentRequest) Validate() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (r GetAttachmentContentRequest) Validate() bool {
|
||||
return r.Variant == "" || r.Variant == "original"
|
||||
}
|
||||
|
||||
func ToAttachmentResponse(a model.Attachment) AttachmentResponse {
|
||||
variants := make([]VariantResponse, 0)
|
||||
return AttachmentResponse{
|
||||
|
||||
@@ -113,8 +113,19 @@ func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
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
|
||||
|
||||
@@ -64,11 +64,14 @@ func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
err := h.service.Logout(r.Context(), token)
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
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")
|
||||
@@ -203,6 +204,10 @@ func (s *AttachmentService) GetContent(
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady {
|
||||
return nil, "", ErrAttachmentNotReady
|
||||
}
|
||||
|
||||
out, err := s.s3.Get(ctx, row.S3Key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
|
||||
@@ -19,8 +19,9 @@ const sessionCacheTTL = 60 * time.Second
|
||||
const cacheOpTimeout = 300 * time.Millisecond
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrSessionCacheUnavailable = errors.New("session cache unavailable")
|
||||
)
|
||||
|
||||
type authQueries interface {
|
||||
@@ -118,7 +119,9 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
s.cacheDel(ctx, cacheKey(tokenHash))
|
||||
if err := s.cacheDel(ctx, cacheKey(tokenHash)); err != nil {
|
||||
return ErrSessionCacheUnavailable
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
@@ -169,9 +172,9 @@ func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, tt
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheDel(ctx context.Context, key string) {
|
||||
func (s *AuthService) cacheDel(ctx context.Context, key string) error {
|
||||
if s.cache == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
@@ -179,5 +182,7 @@ func (s *AuthService) cacheDel(ctx context.Context, key string) {
|
||||
|
||||
if err := s.cache.Del(cctx, key).Err(); err != nil {
|
||||
s.log.Warn("session cache delete failed", "error", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
|
||||
var (
|
||||
ErrMessageChatNotFound = errors.New("chat not found")
|
||||
ErrAttachmentNotReady = errors.New("attachment not ready")
|
||||
ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request")
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user