lab4: S3-вложения, presigned upload и проверки
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
attachmentService "mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(
|
||||
ctx context.Context,
|
||||
req oas.UploadAttachmentReq,
|
||||
params oas.UploadAttachmentParams,
|
||||
) (oas.UploadAttachmentRes, error) {
|
||||
body, declared, err := uploadBody(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attachment, err := h.attachments.Upload(ctx, attachmentService.UploadInput{
|
||||
ChatID: params.ChatID,
|
||||
OwnerID: caller(ctx),
|
||||
Filename: params.Filename,
|
||||
DeclaredContentType: declared,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) GetAttachment(
|
||||
ctx context.Context,
|
||||
params oas.GetAttachmentParams,
|
||||
) (oas.GetAttachmentRes, error) {
|
||||
attachment, err := h.attachments.Get(ctx, caller(ctx), params.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(
|
||||
ctx context.Context,
|
||||
params oas.DownloadAttachmentParams,
|
||||
) (oas.DownloadAttachmentRes, error) {
|
||||
if variant, ok := params.Variant.Get(); ok && variant != oas.DownloadAttachmentVariantOriginal {
|
||||
return nil, fmt.Errorf("%w: variant %q is not available", domain.ErrNotFound, variant)
|
||||
}
|
||||
|
||||
attachment, body, err := h.attachments.Open(ctx, caller(ctx), params.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The generated transport copies the body after the handler returns. Close
|
||||
// the S3 stream when the client disconnects; closeOnEOF covers the normal
|
||||
// path.
|
||||
_ = context.AfterFunc(ctx, func() { _ = body.Close() })
|
||||
|
||||
requestID := oas.NewOptString(requestIDFromContext(ctx))
|
||||
reader := closeOnEOF{ReadCloser: body}
|
||||
|
||||
switch attachment.ContentType {
|
||||
case "image/png":
|
||||
return &oas.DownloadAttachmentOKImagePNGHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImagePNG{Data: reader},
|
||||
}, nil
|
||||
case "image/jpeg":
|
||||
return &oas.DownloadAttachmentOKImageJpegHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImageJpeg{Data: reader},
|
||||
}, nil
|
||||
default:
|
||||
_ = body.Close()
|
||||
|
||||
return nil, fmt.Errorf("%w: unexpected content type %q", domain.ErrUnavailable, attachment.ContentType)
|
||||
}
|
||||
}
|
||||
|
||||
func uploadBody(req oas.UploadAttachmentReq) (io.Reader, string, error) {
|
||||
switch typed := req.(type) {
|
||||
case *oas.UploadAttachmentReqImagePNG:
|
||||
return typed.Data, "image/png", nil
|
||||
case *oas.UploadAttachmentReqImageJpeg:
|
||||
return typed.Data, "image/jpeg", nil
|
||||
default:
|
||||
return nil, "", fmt.Errorf("%w: request body must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentResponse(attachment domain.Attachment) oas.Attachment {
|
||||
response := oas.Attachment{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
SizeBytes: int(attachment.SizeBytes),
|
||||
SHA256: attachment.SHA256,
|
||||
Status: oas.AttachmentStatusReady,
|
||||
Variants: []oas.Variant{},
|
||||
ErrorCode: oas.NilString{Null: true},
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
}
|
||||
|
||||
switch attachment.ContentType {
|
||||
case "image/png":
|
||||
response.ContentType = oas.AttachmentContentTypeImagePNG
|
||||
case "image/jpeg":
|
||||
response.ContentType = oas.AttachmentContentTypeImageJpeg
|
||||
default:
|
||||
response.ContentType = oas.AttachmentContentType(attachment.ContentType)
|
||||
}
|
||||
|
||||
if attachment.ErrorCode != nil {
|
||||
response.ErrorCode = oas.NilString{Value: *attachment.ErrorCode}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
type closeOnEOF struct {
|
||||
io.ReadCloser
|
||||
}
|
||||
|
||||
func (r closeOnEOF) Read(p []byte) (int, error) {
|
||||
n, err := r.ReadCloser.Read(p)
|
||||
if err != nil {
|
||||
_ = r.Close()
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
@@ -3,22 +3,36 @@ package rest
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// attachmentUploadPath matches POST /api/v1/chats/{chat_id}/attachments. The
|
||||
// UUID syntax is not validated here; this middleware only selects a body limit,
|
||||
// and the generated transport rejects malformed identifiers later.
|
||||
var attachmentUploadPath = regexp.MustCompile(`^/api/v1/chats/[^/]+/attachments$`)
|
||||
|
||||
// bodyLimitMiddleware bounds the request body before it reaches the generated
|
||||
// transport. Without it the JSON decoders read the whole body into memory before
|
||||
// any schema check or authentication happens, so an oversized request to a public
|
||||
// endpoint (for example POST /api/v1/users) could exhaust the replica's memory.
|
||||
//
|
||||
// The declared length is rejected early with 413; a client that lies about
|
||||
// Content-Length is cut off by http.MaxBytesReader, which also makes the server
|
||||
// close the connection instead of reading the rest.
|
||||
func bodyLimitMiddleware(limit int64, log *slog.Logger, next http.Handler) http.Handler {
|
||||
if limit <= 0 {
|
||||
// transport. JSON endpoints keep the small default limit; the attachment upload
|
||||
// gets its own larger limit. Without this split the 10 MiB upload would be
|
||||
// rejected before the handler, and raising the global limit would let any
|
||||
// public JSON endpoint read a 10 MiB body.
|
||||
func bodyLimitMiddleware(
|
||||
defaultLimit, uploadLimit int64,
|
||||
log *slog.Logger,
|
||||
next http.Handler,
|
||||
) http.Handler {
|
||||
if defaultLimit <= 0 && uploadLimit <= 0 {
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
limit := limitForRequest(r, defaultLimit, uploadLimit)
|
||||
if limit <= 0 {
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.ContentLength > limit {
|
||||
logRejected(r.Context(), log, r, http.StatusRequestEntityTooLarge, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusRequestEntityTooLarge)
|
||||
@@ -33,3 +47,11 @@ func bodyLimitMiddleware(limit int64, log *slog.Logger, next http.Handler) http.
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func limitForRequest(r *http.Request, defaultLimit, uploadLimit int64) int64 {
|
||||
if r.Method == http.MethodPost && attachmentUploadPath.MatchString(r.URL.Path) {
|
||||
return uploadLimit
|
||||
}
|
||||
|
||||
return defaultLimit
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLimitForRequest(t *testing.T) {
|
||||
const (
|
||||
defaultLimit = 1024
|
||||
uploadLimit = 10 << 20
|
||||
)
|
||||
|
||||
upload, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(uploadLimit), limitForRequest(upload, defaultLimit, uploadLimit))
|
||||
|
||||
messages, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/messages", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(defaultLimit), limitForRequest(messages, defaultLimit, uploadLimit))
|
||||
|
||||
presign, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(defaultLimit), limitForRequest(presign, defaultLimit, uploadLimit))
|
||||
}
|
||||
|
||||
func TestBodyLimitMiddlewareSelectsUploadLimit(t *testing.T) {
|
||||
const (
|
||||
defaultLimit = 16
|
||||
uploadLimit = 64
|
||||
)
|
||||
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(body)
|
||||
})
|
||||
handler := bodyLimitMiddleware(defaultLimit, uploadLimit, nil, next)
|
||||
|
||||
upload := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost,
|
||||
"/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments",
|
||||
strings.NewReader(strings.Repeat("x", 32)),
|
||||
)
|
||||
uploadRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(uploadRecorder, upload)
|
||||
require.Equal(t, http.StatusOK, uploadRecorder.Code)
|
||||
|
||||
jsonRequest := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost,
|
||||
"/api/v1/chats/11111111-1111-4111-8111-111111111111/messages",
|
||||
strings.NewReader(strings.Repeat("x", 32)),
|
||||
)
|
||||
jsonRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(jsonRecorder, jsonRequest)
|
||||
require.Equal(t, http.StatusRequestEntityTooLarge, jsonRecorder.Code)
|
||||
}
|
||||
@@ -53,12 +53,17 @@ func statusForDomainError(err error) int {
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, domain.ErrUsernameTaken),
|
||||
errors.Is(err, domain.ErrConflict),
|
||||
errors.Is(err, domain.ErrIdempotency):
|
||||
errors.Is(err, domain.ErrIdempotency),
|
||||
errors.Is(err, domain.ErrIncomplete):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, domain.ErrValidation),
|
||||
errors.Is(err, domain.ErrUnknownMember),
|
||||
errors.Is(err, domain.ErrInvalidCursor):
|
||||
return http.StatusBadRequest
|
||||
case errors.Is(err, domain.ErrTooLarge):
|
||||
return http.StatusRequestEntityTooLarge
|
||||
case errors.Is(err, domain.ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
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 {
|
||||
return uuid.Nil, fmt.Errorf("%w: %w", domain.ErrUnauthenticated, 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.StatusOK, 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
|
||||
}
|
||||
@@ -7,12 +7,15 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
attachmentService "mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
@@ -51,14 +54,23 @@ type SessionService interface {
|
||||
Revoke(ctx context.Context, userID uuid.UUID, token string) error
|
||||
}
|
||||
|
||||
type AttachmentService interface {
|
||||
Upload(ctx context.Context, input attachmentService.UploadInput) (domain.Attachment, error)
|
||||
Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error)
|
||||
Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error)
|
||||
Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error)
|
||||
Complete(ctx context.Context, ownerID, id uuid.UUID, sha256 string) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
oas.UnimplementedHandler
|
||||
|
||||
users UserService
|
||||
chats ChatService
|
||||
messages MessageService
|
||||
health HealthChecker
|
||||
sessions SessionService
|
||||
users UserService
|
||||
chats ChatService
|
||||
messages MessageService
|
||||
attachments AttachmentService
|
||||
health HealthChecker
|
||||
sessions SessionService
|
||||
}
|
||||
|
||||
var noCursor *domain.Cursor
|
||||
@@ -67,15 +79,17 @@ func NewHandler(
|
||||
users UserService,
|
||||
chats ChatService,
|
||||
messages MessageService,
|
||||
attachments AttachmentService,
|
||||
health HealthChecker,
|
||||
sessions SessionService,
|
||||
) *Handler {
|
||||
return &Handler{
|
||||
users: users,
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
health: health,
|
||||
sessions: sessions,
|
||||
users: users,
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
attachments: attachments,
|
||||
health: health,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,9 +252,10 @@ func (h *Handler) CreateMessage(
|
||||
}
|
||||
|
||||
message, err := h.messages.Send(ctx, domain.MessageDraft{
|
||||
ChatID: params.ChatID,
|
||||
SenderID: callerID,
|
||||
Text: req.Text,
|
||||
ChatID: params.ChatID,
|
||||
SenderID: callerID,
|
||||
Text: req.Text,
|
||||
AttachmentIDs: req.AttachmentIds,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: params.IdempotencyKey,
|
||||
RequestHash: fingerprint,
|
||||
@@ -260,9 +275,16 @@ func (h *Handler) CreateMessage(
|
||||
// order of the client JSON cannot change the fingerprint, while a different
|
||||
// payload with the same Idempotency-Key can (contract 1.3.0).
|
||||
func messageFingerprint(req *oas.CreateMessage) ([sha256.Size]byte, error) {
|
||||
ids := make([]uuid.UUID, 0, len(req.AttachmentIds))
|
||||
ids = append(ids, req.AttachmentIds...)
|
||||
slices.SortFunc(ids, func(left, right uuid.UUID) int {
|
||||
return bytes.Compare(left[:], right[:])
|
||||
})
|
||||
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
}{Text: req.Text})
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
||||
}{Text: req.Text, AttachmentIDs: ids})
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("encode message payload: %w", err)
|
||||
}
|
||||
@@ -396,11 +418,15 @@ func chatResponse(chat domain.Chat) oas.Chat {
|
||||
}
|
||||
|
||||
func messageResponse(message domain.Message) oas.Message {
|
||||
ids := make([]uuid.UUID, 0, len(message.AttachmentIDs))
|
||||
ids = append(ids, message.AttachmentIDs...)
|
||||
|
||||
return oas.Message{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
AttachmentIds: ids,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ func TestInstanceIDMiddleware(t *testing.T) {
|
||||
|
||||
instanceIDMiddleware("api-1", test.handler).ServeHTTP(
|
||||
recorder,
|
||||
httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil),
|
||||
httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/v1/users/me", nil),
|
||||
)
|
||||
|
||||
assert.Equal(t, test.wantID, recorder.Header().Get(instanceIDHeader))
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
|
||||
"^[a-f0-9]{64}$": ogenregex.MustCompile("^[a-f0-9]{64}$"),
|
||||
"^[a-z0-9_]{3,32}$": ogenregex.MustCompile("^[a-z0-9_]{3,32}$"),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// setDefaults set default value of fields.
|
||||
func (s *CreateMessage) setDefaults() {
|
||||
{
|
||||
var defaultVal0 []uuid.UUID
|
||||
s.AttachmentIds = defaultVal0
|
||||
}
|
||||
}
|
||||
@@ -529,6 +529,266 @@ func (s *Server) handleCurrentUserRequest(args [0]string, argsEscaped bool, w ht
|
||||
}
|
||||
}
|
||||
|
||||
// handleDownloadAttachmentRequest handles downloadAttachment operation.
|
||||
//
|
||||
// Скачать байты через авторизованный API.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}/content
|
||||
func (s *Server) handleDownloadAttachmentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
ctx := r.Context()
|
||||
|
||||
var (
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: DownloadAttachmentOperation,
|
||||
ID: "downloadAttachment",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securityBearerAuth(ctx, DownloadAttachmentOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "BearerAuth",
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("Security:BearerAuth", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
defer recordError("Security", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeDownloadAttachmentParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response DownloadAttachmentRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: DownloadAttachmentOperation,
|
||||
OperationSummary: "Скачать байты через авторизованный API",
|
||||
OperationID: "downloadAttachment",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}: params.AttachmentID,
|
||||
{
|
||||
Name: "variant",
|
||||
In: "query",
|
||||
}: params.Variant,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = DownloadAttachmentParams
|
||||
Response = DownloadAttachmentRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackDownloadAttachmentParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.DownloadAttachment(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.DownloadAttachment(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
defer recordError("Internal", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeDownloadAttachmentResponse(response, w); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetAttachmentRequest handles getAttachment operation.
|
||||
//
|
||||
// Метаданные вложения, доступ участникам чата.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
func (s *Server) handleGetAttachmentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
ctx := r.Context()
|
||||
|
||||
var (
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: GetAttachmentOperation,
|
||||
ID: "getAttachment",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securityBearerAuth(ctx, GetAttachmentOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "BearerAuth",
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("Security:BearerAuth", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
defer recordError("Security", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeGetAttachmentParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response GetAttachmentRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetAttachmentOperation,
|
||||
OperationSummary: "Метаданные вложения, доступ участникам чата",
|
||||
OperationID: "getAttachment",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}: params.AttachmentID,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetAttachmentParams
|
||||
Response = GetAttachmentRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetAttachmentParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetAttachment(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetAttachment(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
defer recordError("Internal", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeGetAttachmentResponse(response, w); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetChatRequest handles getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
@@ -1251,3 +1511,150 @@ func (s *Server) handleRevokeSessionRequest(args [0]string, argsEscaped bool, w
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleUploadAttachmentRequest handles uploadAttachment operation.
|
||||
//
|
||||
// Принять один PNG/JPEG, до 10 MiB.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/attachments
|
||||
func (s *Server) handleUploadAttachmentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
ctx := r.Context()
|
||||
|
||||
var (
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: UploadAttachmentOperation,
|
||||
ID: "uploadAttachment",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securityBearerAuth(ctx, UploadAttachmentOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "BearerAuth",
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("Security:BearerAuth", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
defer recordError("Security", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeUploadAttachmentParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeUploadAttachmentRequest(r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeRequestError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeRequest", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := close(); err != nil {
|
||||
recordError("CloseRequest", err)
|
||||
}
|
||||
}()
|
||||
|
||||
var response UploadAttachmentRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: UploadAttachmentOperation,
|
||||
OperationSummary: "Принять один PNG/JPEG, до 10 MiB",
|
||||
OperationID: "uploadAttachment",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}: params.ChatID,
|
||||
{
|
||||
Name: "filename",
|
||||
In: "query",
|
||||
}: params.Filename,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = UploadAttachmentReq
|
||||
Params = UploadAttachmentParams
|
||||
Response = UploadAttachmentRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackUploadAttachmentParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.UploadAttachment(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.UploadAttachment(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
defer recordError("Internal", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeUploadAttachmentResponse(response, w); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,14 @@ type CurrentUserRes interface {
|
||||
currentUserRes()
|
||||
}
|
||||
|
||||
type DownloadAttachmentRes interface {
|
||||
downloadAttachmentRes()
|
||||
}
|
||||
|
||||
type GetAttachmentRes interface {
|
||||
getAttachmentRes()
|
||||
}
|
||||
|
||||
type GetChatRes interface {
|
||||
getChatRes()
|
||||
}
|
||||
@@ -44,3 +52,11 @@ type RegisterUserRes interface {
|
||||
type RevokeSessionRes interface {
|
||||
revokeSessionRes()
|
||||
}
|
||||
|
||||
type UploadAttachmentReq interface {
|
||||
uploadAttachmentReq()
|
||||
}
|
||||
|
||||
type UploadAttachmentRes interface {
|
||||
uploadAttachmentRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,15 +6,18 @@ package oas
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
CreateChatOperation OperationName = "CreateChat"
|
||||
CreateMessageOperation OperationName = "CreateMessage"
|
||||
CreateSessionOperation OperationName = "CreateSession"
|
||||
CurrentUserOperation OperationName = "CurrentUser"
|
||||
GetChatOperation OperationName = "GetChat"
|
||||
ListChatsOperation OperationName = "ListChats"
|
||||
ListMessagesOperation OperationName = "ListMessages"
|
||||
LivenessOperation OperationName = "Liveness"
|
||||
ReadinessOperation OperationName = "Readiness"
|
||||
RegisterUserOperation OperationName = "RegisterUser"
|
||||
RevokeSessionOperation OperationName = "RevokeSession"
|
||||
CreateChatOperation OperationName = "CreateChat"
|
||||
CreateMessageOperation OperationName = "CreateMessage"
|
||||
CreateSessionOperation OperationName = "CreateSession"
|
||||
CurrentUserOperation OperationName = "CurrentUser"
|
||||
DownloadAttachmentOperation OperationName = "DownloadAttachment"
|
||||
GetAttachmentOperation OperationName = "GetAttachment"
|
||||
GetChatOperation OperationName = "GetChat"
|
||||
ListChatsOperation OperationName = "ListChats"
|
||||
ListMessagesOperation OperationName = "ListMessages"
|
||||
LivenessOperation OperationName = "Liveness"
|
||||
ReadinessOperation OperationName = "Readiness"
|
||||
RegisterUserOperation OperationName = "RegisterUser"
|
||||
RevokeSessionOperation OperationName = "RevokeSession"
|
||||
UploadAttachmentOperation OperationName = "UploadAttachment"
|
||||
)
|
||||
|
||||
@@ -147,6 +147,208 @@ func decodeCreateMessageParams(args [1]string, argsEscaped bool, r *http.Request
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// DownloadAttachmentParams is parameters of downloadAttachment operation.
|
||||
type DownloadAttachmentParams struct {
|
||||
AttachmentID uuid.UUID
|
||||
Variant OptDownloadAttachmentVariant `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackDownloadAttachmentParams(packed middleware.Parameters) (params DownloadAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttachmentID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "variant",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Variant = v.(OptDownloadAttachmentVariant)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeDownloadAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params DownloadAttachmentParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: attachment_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "attachment_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.AttachmentID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Set default value for query: variant.
|
||||
{
|
||||
val := DownloadAttachmentVariant("original")
|
||||
params.Variant.SetTo(val)
|
||||
}
|
||||
// Decode query: variant.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "variant",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotVariantVal DownloadAttachmentVariant
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotVariantVal = DownloadAttachmentVariant(c)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Variant.SetTo(paramsDotVariantVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Variant.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "variant",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetAttachmentParams is parameters of getAttachment operation.
|
||||
type GetAttachmentParams struct {
|
||||
AttachmentID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackGetAttachmentParams(packed middleware.Parameters) (params GetAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttachmentID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params GetAttachmentParams, _ error) {
|
||||
// Decode path: attachment_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "attachment_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.AttachmentID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetChatParams is parameters of getChat operation.
|
||||
type GetChatParams struct {
|
||||
ChatID uuid.UUID
|
||||
@@ -608,3 +810,133 @@ func decodeListMessagesParams(args [1]string, argsEscaped bool, r *http.Request)
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// UploadAttachmentParams is parameters of uploadAttachment operation.
|
||||
type UploadAttachmentParams struct {
|
||||
ChatID uuid.UUID
|
||||
Filename string
|
||||
}
|
||||
|
||||
func unpackUploadAttachmentParams(packed middleware.Parameters) (params UploadAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "filename",
|
||||
In: "query",
|
||||
}
|
||||
params.Filename = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeUploadAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params UploadAttachmentParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: filename.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "filename",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.Filename = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 255,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.Filename)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "filename",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
@@ -250,3 +250,42 @@ func (s *Server) decodeRegisterUserRequest(r *http.Request) (
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeUploadAttachmentRequest(r *http.Request) (
|
||||
req UploadAttachmentReq,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "image/jpeg":
|
||||
reader := r.Body
|
||||
request := UploadAttachmentReqImageJpeg{Data: reader}
|
||||
return &request, rawBody, close, nil
|
||||
case ct == "image/png":
|
||||
reader := r.Body
|
||||
request := UploadAttachmentReqImagePNG{Data: reader}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,10 +11,16 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn10AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn11AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn6AllowedHeaders = map[string]string{
|
||||
"POST": "Authorization",
|
||||
}
|
||||
rn13AllowedHeaders = map[string]string{
|
||||
rn17AllowedHeaders = map[string]string{
|
||||
"DELETE": "Authorization",
|
||||
}
|
||||
rn1AllowedHeaders = map[string]string{
|
||||
@@ -24,11 +30,14 @@ var (
|
||||
rn3AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn19AllowedHeaders = map[string]string{
|
||||
"POST": "Authorization,Content-Type",
|
||||
}
|
||||
rn4AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
"POST": "Authorization,Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn12AllowedHeaders = map[string]string{
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
@@ -99,47 +108,45 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "auth/sessions"
|
||||
case 'a': // Prefix: "a"
|
||||
|
||||
if l := len("auth/sessions"); len(elem) >= l && elem[0:l] == "auth/sessions" {
|
||||
if l := len("a"); len(elem) >= l && elem[0:l] == "a" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleCreateSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn6AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
case 't': // Prefix: "ttachments/"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
if l := len("ttachments/"); len(elem) >= l && elem[0:l] == "ttachments/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "attachment_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "DELETE":
|
||||
s.handleRevokeSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
case "GET":
|
||||
s.handleGetAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn13AllowedHeaders,
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn10AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -147,6 +154,86 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/content"
|
||||
|
||||
if l := len("/content"); len(elem) >= l && elem[0:l] == "/content" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleDownloadAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn11AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uth/sessions"
|
||||
|
||||
if l := len("uth/sessions"); len(elem) >= l && elem[0:l] == "uth/sessions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleCreateSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn6AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "DELETE":
|
||||
s.handleRevokeSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn17AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -211,35 +298,76 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/messages"
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/messages"); len(elem) >= l && elem[0:l] == "/messages" {
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMessagesRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateMessageRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn4AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "attachments"
|
||||
|
||||
if l := len("attachments"); len(elem) >= l && elem[0:l] == "attachments" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleUploadAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn19AllowedHeaders,
|
||||
acceptPost: "image/jpeg,image/png",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'm': // Prefix: "messages"
|
||||
|
||||
if l := len("messages"); len(elem) >= l && elem[0:l] == "messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMessagesRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateMessageRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn4AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
@@ -261,7 +389,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn12AllowedHeaders,
|
||||
allowedHeaders: rn16AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -475,47 +603,94 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "auth/sessions"
|
||||
case 'a': // Prefix: "a"
|
||||
|
||||
if l := len("auth/sessions"); len(elem) >= l && elem[0:l] == "auth/sessions" {
|
||||
if l := len("a"); len(elem) >= l && elem[0:l] == "a" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = CreateSessionOperation
|
||||
r.summary = "Вход: Basic username:password; выдаёт сессию"
|
||||
r.operationID = "createSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/auth/sessions"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
case 't': // Prefix: "ttachments/"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
if l := len("ttachments/"); len(elem) >= l && elem[0:l] == "ttachments/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "attachment_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetAttachmentOperation
|
||||
r.summary = "Метаданные вложения, доступ участникам чата"
|
||||
r.operationID = "getAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/attachments/{attachment_id}"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/content"
|
||||
|
||||
if l := len("/content"); len(elem) >= l && elem[0:l] == "/content" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = DownloadAttachmentOperation
|
||||
r.summary = "Скачать байты через авторизованный API"
|
||||
r.operationID = "downloadAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/attachments/{attachment_id}/content"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uth/sessions"
|
||||
|
||||
if l := len("uth/sessions"); len(elem) >= l && elem[0:l] == "uth/sessions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "DELETE":
|
||||
r.name = RevokeSessionOperation
|
||||
r.summary = "Отозвать текущую сессию"
|
||||
r.operationID = "revokeSession"
|
||||
case "POST":
|
||||
r.name = CreateSessionOperation
|
||||
r.summary = "Вход: Basic username:password; выдаёт сессию"
|
||||
r.operationID = "createSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/auth/sessions/current"
|
||||
r.pathPattern = "/api/v1/auth/sessions"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
@@ -523,6 +698,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "DELETE":
|
||||
r.name = RevokeSessionOperation
|
||||
r.summary = "Отозвать текущую сессию"
|
||||
r.operationID = "revokeSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/auth/sessions/current"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -592,38 +794,77 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/messages"
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/messages"); len(elem) >= l && elem[0:l] == "/messages" {
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMessagesOperation
|
||||
r.summary = "Сообщения по (created_at, id) по возрастанию"
|
||||
r.operationID = "listMessages"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateMessageOperation
|
||||
r.summary = "Отправить сообщение"
|
||||
r.operationID = "createMessage"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "attachments"
|
||||
|
||||
if l := len("attachments"); len(elem) >= l && elem[0:l] == "attachments" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = UploadAttachmentOperation
|
||||
r.summary = "Принять один PNG/JPEG, до 10 MiB"
|
||||
r.operationID = "uploadAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/attachments"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'm': // Prefix: "messages"
|
||||
|
||||
if l := len("messages"); len(elem) >= l && elem[0:l] == "messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMessagesOperation
|
||||
r.summary = "Сообщения по (created_at, id) по возрастанию"
|
||||
r.operationID = "listMessages"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateMessageOperation
|
||||
r.summary = "Отправить сообщение"
|
||||
r.operationID = "createMessage"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -62,13 +62,16 @@ func GetRolesForBasicAuth(operation string) []string {
|
||||
|
||||
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||
var operationRolesBearerAuth = map[string][]string{
|
||||
CreateChatOperation: []string{},
|
||||
CreateMessageOperation: []string{},
|
||||
CurrentUserOperation: []string{},
|
||||
GetChatOperation: []string{},
|
||||
ListChatsOperation: []string{},
|
||||
ListMessagesOperation: []string{},
|
||||
RevokeSessionOperation: []string{},
|
||||
CreateChatOperation: []string{},
|
||||
CreateMessageOperation: []string{},
|
||||
CurrentUserOperation: []string{},
|
||||
DownloadAttachmentOperation: []string{},
|
||||
GetAttachmentOperation: []string{},
|
||||
GetChatOperation: []string{},
|
||||
ListChatsOperation: []string{},
|
||||
ListMessagesOperation: []string{},
|
||||
RevokeSessionOperation: []string{},
|
||||
UploadAttachmentOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||
|
||||
@@ -32,6 +32,18 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/users/me
|
||||
CurrentUser(ctx context.Context) (CurrentUserRes, error)
|
||||
// DownloadAttachment implements downloadAttachment operation.
|
||||
//
|
||||
// Скачать байты через авторизованный API.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}/content
|
||||
DownloadAttachment(ctx context.Context, params DownloadAttachmentParams) (DownloadAttachmentRes, error)
|
||||
// GetAttachment implements getAttachment operation.
|
||||
//
|
||||
// Метаданные вложения, доступ участникам чата.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
GetAttachment(ctx context.Context, params GetAttachmentParams) (GetAttachmentRes, error)
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
@@ -74,6 +86,12 @@ type Handler interface {
|
||||
//
|
||||
// DELETE /api/v1/auth/sessions/current
|
||||
RevokeSession(ctx context.Context) (RevokeSessionRes, error)
|
||||
// UploadAttachment implements uploadAttachment operation.
|
||||
//
|
||||
// Принять один PNG/JPEG, до 10 MiB.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/attachments
|
||||
UploadAttachment(ctx context.Context, req UploadAttachmentReq, params UploadAttachmentParams) (UploadAttachmentRes, error)
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
|
||||
@@ -49,6 +49,24 @@ func (UnimplementedHandler) CurrentUser(ctx context.Context) (r CurrentUserRes,
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DownloadAttachment implements downloadAttachment operation.
|
||||
//
|
||||
// Скачать байты через авторизованный API.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}/content
|
||||
func (UnimplementedHandler) DownloadAttachment(ctx context.Context, params DownloadAttachmentParams) (r DownloadAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetAttachment implements getAttachment operation.
|
||||
//
|
||||
// Метаданные вложения, доступ участникам чата.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
func (UnimplementedHandler) GetAttachment(ctx context.Context, params GetAttachmentParams) (r GetAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
@@ -111,3 +129,12 @@ func (UnimplementedHandler) RegisterUser(ctx context.Context, req *CreateUser) (
|
||||
func (UnimplementedHandler) RevokeSession(ctx context.Context) (r RevokeSessionRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UploadAttachment implements uploadAttachment operation.
|
||||
//
|
||||
// Принять один PNG/JPEG, до 10 MiB.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/attachments
|
||||
func (UnimplementedHandler) UploadAttachment(ctx context.Context, req UploadAttachmentReq, params UploadAttachmentParams) (r UploadAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,413 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockAttachmentService creates a new instance of MockAttachmentService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockAttachmentService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockAttachmentService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockAttachmentService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockAttachmentService is an autogenerated mock type for the AttachmentService type
|
||||
type MockAttachmentService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockAttachmentService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockAttachmentService) EXPECT() *MockAttachmentService_Expecter {
|
||||
return &MockAttachmentService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Complete provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Complete(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, ownerID, id, sha256)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Complete")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, ownerID, id, sha256)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, ownerID, id, sha256)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, string) error); ok {
|
||||
r1 = returnFunc(ctx, ownerID, id, sha256)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Complete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Complete'
|
||||
type MockAttachmentService_Complete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Complete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
// - sha256 string
|
||||
func (_e *MockAttachmentService_Expecter) Complete(ctx any, ownerID any, id any, sha256 any) *MockAttachmentService_Complete_Call {
|
||||
return &MockAttachmentService_Complete_Call{Call: _e.mock.On("Complete", ctx, ownerID, id, sha256)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string)) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) Return(attachment domain.Attachment, err error) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string) (domain.Attachment, error)) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Get(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, callerID, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, callerID, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockAttachmentService_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
func (_e *MockAttachmentService_Expecter) Get(ctx any, callerID any, id any) *MockAttachmentService_Get_Call {
|
||||
return &MockAttachmentService_Get_Call{Call: _e.mock.On("Get", ctx, callerID, id)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID)) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) Return(attachment domain.Attachment, err error) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Open provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Open(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
|
||||
ret := _mock.Called(ctx, callerID, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Open")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 io.ReadCloser
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, io.ReadCloser, error)); ok {
|
||||
return returnFunc(ctx, callerID, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) io.ReadCloser); ok {
|
||||
r1 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
if ret.Get(1) != nil {
|
||||
r1 = ret.Get(1).(io.ReadCloser)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r2 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockAttachmentService_Open_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Open'
|
||||
type MockAttachmentService_Open_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Open is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
func (_e *MockAttachmentService_Expecter) Open(ctx any, callerID any, id any) *MockAttachmentService_Open_Call {
|
||||
return &MockAttachmentService_Open_Call{Call: _e.mock.On("Open", ctx, callerID, id)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Open_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID)) *MockAttachmentService_Open_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Open_Call) Return(attachment domain.Attachment, readCloser io.ReadCloser, err error) *MockAttachmentService_Open_Call {
|
||||
_c.Call.Return(attachment, readCloser, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Open_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error)) *MockAttachmentService_Open_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Presign provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
|
||||
ret := _mock.Called(ctx, request)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Presign")
|
||||
}
|
||||
|
||||
var r0 domain.PresignResult
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.PresignRequest) (domain.PresignResult, error)); ok {
|
||||
return returnFunc(ctx, request)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.PresignRequest) domain.PresignResult); ok {
|
||||
r0 = returnFunc(ctx, request)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.PresignResult)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.PresignRequest) error); ok {
|
||||
r1 = returnFunc(ctx, request)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Presign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Presign'
|
||||
type MockAttachmentService_Presign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Presign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - request domain.PresignRequest
|
||||
func (_e *MockAttachmentService_Expecter) Presign(ctx any, request any) *MockAttachmentService_Presign_Call {
|
||||
return &MockAttachmentService_Presign_Call{Call: _e.mock.On("Presign", ctx, request)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) Run(run func(ctx context.Context, request domain.PresignRequest)) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.PresignRequest
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.PresignRequest)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) Return(presignResult domain.PresignResult, err error) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Return(presignResult, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) RunAndReturn(run func(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error)) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Upload provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Upload(ctx context.Context, input attachment.UploadInput) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, input)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Upload")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, attachment.UploadInput) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, input)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, attachment.UploadInput) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, input)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, attachment.UploadInput) error); ok {
|
||||
r1 = returnFunc(ctx, input)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Upload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Upload'
|
||||
type MockAttachmentService_Upload_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Upload is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - input attachment.UploadInput
|
||||
func (_e *MockAttachmentService_Expecter) Upload(ctx any, input any) *MockAttachmentService_Upload_Call {
|
||||
return &MockAttachmentService_Upload_Call{Call: _e.mock.On("Upload", ctx, input)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) Run(run func(ctx context.Context, input attachment.UploadInput)) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 attachment.UploadInput
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(attachment.UploadInput)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) Return(attachment1 domain.Attachment, err error) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Return(attachment1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) RunAndReturn(run func(ctx context.Context, input attachment.UploadInput) (domain.Attachment, error)) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSessionResolver creates a new instance of MockSessionResolver. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSessionResolver(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSessionResolver {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSessionResolver{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSessionResolver is an autogenerated mock type for the SessionResolver type
|
||||
type MockSessionResolver struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSessionResolver_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSessionResolver) EXPECT() *MockSessionResolver_Expecter {
|
||||
return &MockSessionResolver_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockSessionResolver
|
||||
func (_mock *MockSessionResolver) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionResolver_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockSessionResolver_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - token string
|
||||
func (_e *MockSessionResolver_Expecter) Resolve(ctx any, token any) *MockSessionResolver_Resolve_Call {
|
||||
return &MockSessionResolver_Resolve_Call{Call: _e.mock.On("Resolve", ctx, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) Run(run func(ctx context.Context, token string)) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) Return(user domain.User, err error) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) RunAndReturn(run func(ctx context.Context, token string) (domain.User, error)) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -10,8 +10,9 @@ import (
|
||||
func NewRouter(
|
||||
handler oas.Handler,
|
||||
security oas.SecurityHandler,
|
||||
extensions *Extensions,
|
||||
log *slog.Logger,
|
||||
maxBodyBytes int64,
|
||||
maxBodyBytes, maxUploadBytes int64,
|
||||
) (http.Handler, error) {
|
||||
server, err := oas.NewServer(
|
||||
handler,
|
||||
@@ -25,7 +26,19 @@ func NewRouter(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
if extensions != nil {
|
||||
// These routes are an optional contract extension (presigned uploads).
|
||||
// They live outside the generated server so contracts/openapi.json stays
|
||||
// byte-identical to the mandatory contract.
|
||||
mux.Handle("/api/v1/chats/{chat_id}/attachments/presign", extensions.Presign())
|
||||
mux.Handle("/api/v1/attachments/{attachment_id}/complete", extensions.Complete())
|
||||
}
|
||||
|
||||
mux.Handle("/", server)
|
||||
|
||||
return requestIDMiddleware(
|
||||
instanceIDMiddleware(InstanceID(), bodyLimitMiddleware(maxBodyBytes, log, server)),
|
||||
instanceIDMiddleware(InstanceID(), bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)),
|
||||
), nil
|
||||
}
|
||||
|
||||
@@ -44,11 +44,12 @@ type httpResult struct {
|
||||
}
|
||||
|
||||
type routerFixture struct {
|
||||
users *mocks.MockUserService
|
||||
chats *mocks.MockChatService
|
||||
messages *mocks.MockMessageService
|
||||
health *mocks.MockHealthChecker
|
||||
sessions *mocks.MockSessionActions
|
||||
users *mocks.MockUserService
|
||||
chats *mocks.MockChatService
|
||||
messages *mocks.MockMessageService
|
||||
attachments *mocks.MockAttachmentService
|
||||
health *mocks.MockHealthChecker
|
||||
sessions *mocks.MockSessionActions
|
||||
|
||||
server *httptest.Server
|
||||
}
|
||||
@@ -60,18 +61,28 @@ func newRouterFixture(t *testing.T) *routerFixture {
|
||||
t.Helper()
|
||||
|
||||
fixture := &routerFixture{
|
||||
users: mocks.NewMockUserService(t),
|
||||
chats: mocks.NewMockChatService(t),
|
||||
messages: mocks.NewMockMessageService(t),
|
||||
health: mocks.NewMockHealthChecker(t),
|
||||
sessions: mocks.NewMockSessionActions(t),
|
||||
users: mocks.NewMockUserService(t),
|
||||
chats: mocks.NewMockChatService(t),
|
||||
messages: mocks.NewMockMessageService(t),
|
||||
attachments: mocks.NewMockAttachmentService(t),
|
||||
health: mocks.NewMockHealthChecker(t),
|
||||
sessions: mocks.NewMockSessionActions(t),
|
||||
}
|
||||
|
||||
router, err := rest.NewRouter(
|
||||
rest.NewHandler(fixture.users, fixture.chats, fixture.messages, fixture.health, fixture.sessions),
|
||||
rest.NewHandler(
|
||||
fixture.users,
|
||||
fixture.chats,
|
||||
fixture.messages,
|
||||
fixture.attachments,
|
||||
fixture.health,
|
||||
fixture.sessions,
|
||||
),
|
||||
rest.NewSecurityHandler(fixture.sessions),
|
||||
nil,
|
||||
logger.New(logger.WithLevel(slog.LevelError)),
|
||||
testMaxBodyBytes,
|
||||
testMaxBodyBytes,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user