forked from mtusi2026/mtusi2026lab4
feat: attachments over S3 (grade 3)
This commit is contained in:
+61
-12
@@ -10,12 +10,19 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTL time.Duration
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTL time.Duration
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKeyID string
|
||||
S3SecretAccessKey string
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
@@ -23,6 +30,14 @@ func Load() (Config, error) {
|
||||
if err != nil || ttl <= 0 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
|
||||
}
|
||||
maxUploadBytes, err := positiveInt("MAX_UPLOAD_BYTES", "10485760")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
maxImagePixels, err := positiveInt("MAX_IMAGE_PIXELS", "40000000")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
@@ -31,18 +46,52 @@ func Load() (Config, error) {
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
accessKeyID, err := readSecret("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
secretAccessKey, err := readSecret("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if accessKeyID == "" || secretAccessKey == "" {
|
||||
return Config{}, fmt.Errorf("S3_ACCESS_KEY_ID_FILE and S3_SECRET_ACCESS_KEY_FILE must not be empty")
|
||||
}
|
||||
bucket := getenv("S3_BUCKET", "messenger-attachments")
|
||||
if strings.TrimSpace(bucket) == "" {
|
||||
return Config{}, fmt.Errorf("S3_BUCKET must not be empty")
|
||||
}
|
||||
endpoint := getenv("S3_ENDPOINT", "http://s3:9000")
|
||||
if strings.TrimSpace(endpoint) == "" {
|
||||
return Config{}, fmt.Errorf("S3_ENDPOINT must not be empty")
|
||||
}
|
||||
return Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
SessionTTL: time.Duration(ttl) * time.Second,
|
||||
DatabaseURL: databaseURL,
|
||||
CacheURL: cacheURL,
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
SessionTTL: time.Duration(ttl) * time.Second,
|
||||
DatabaseURL: databaseURL,
|
||||
CacheURL: cacheURL,
|
||||
S3Endpoint: endpoint,
|
||||
S3Region: getenv("S3_REGION", "us-east-1"),
|
||||
S3Bucket: bucket,
|
||||
S3AccessKeyID: accessKeyID,
|
||||
S3SecretAccessKey: secretAccessKey,
|
||||
MaxUploadBytes: maxUploadBytes,
|
||||
MaxImagePixels: maxImagePixels,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
|
||||
|
||||
func positiveInt(key, def string) (int64, error) {
|
||||
value, err := strconv.ParseInt(getenv(key, def), 10, 64)
|
||||
if err != nil || value <= 0 {
|
||||
return 0, fmt.Errorf("%s must be a positive integer", key)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func readSecret(key, def string) (string, error) {
|
||||
path := getenv(key, def)
|
||||
b, err := os.ReadFile(path)
|
||||
|
||||
@@ -29,11 +29,33 @@ func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
AttachmentIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
const (
|
||||
AttachmentReady = "ready"
|
||||
ContentPNG = "image/png"
|
||||
ContentJPEG = "image/jpeg"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
Status string
|
||||
ErrorCode *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
|
||||
@@ -3,9 +3,11 @@ package domain
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
ErrTooLarge = errors.New("payload too large")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"uuid"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := chatIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" {
|
||||
h.fail(w, r, badRequest("filename is required"))
|
||||
return
|
||||
}
|
||||
contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
contentType = ""
|
||||
}
|
||||
attachment, err := h.attachments.Upload(r.Context(), actor(r), chatID, filename, contentType, r.Body)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, toAttachmentResponse(attachment))
|
||||
}
|
||||
|
||||
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := attachmentIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
attachment, err := h.attachments.Get(r.Context(), actor(r), id)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toAttachmentResponse(attachment))
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := attachmentIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
attachment, content, err := h.attachments.Open(r.Context(), actor(r), id, r.URL.Query().Get("variant"))
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
defer content.Close()
|
||||
w.Header().Set("Content-Type", attachment.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, content); err != nil {
|
||||
h.log.Error("attachment download interrupted", "request_id", w.Header().Get(headerRequestID), "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentIDParam(r *http.Request) (uuid.UUID, error) {
|
||||
id, ok := parseUUID(chi.URLParam(r, "attachment_id"))
|
||||
if !ok {
|
||||
return uuid.UUID{}, badRequest("attachment_id must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
+64
-11
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
@@ -18,7 +19,8 @@ type createChatRequest struct {
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text *string `json:"text"`
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs *[]string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
@@ -36,11 +38,36 @@ type chatResponse struct {
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type variantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type attachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []variantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type pageResponse[T any] struct {
|
||||
@@ -106,14 +133,40 @@ func toChatResponse(c domain.Chat) chatResponse {
|
||||
|
||||
func toMessageResponse(m domain.Message) messageResponse {
|
||||
return messageResponse{
|
||||
ID: m.ID.String(),
|
||||
ChatID: m.ChatID.String(),
|
||||
SenderID: m.SenderID.String(),
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
ID: m.ID.String(),
|
||||
ChatID: m.ChatID.String(),
|
||||
SenderID: m.SenderID.String(),
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
AttachmentIDs: toIDStrings(m.AttachmentIDs),
|
||||
}
|
||||
}
|
||||
|
||||
func toAttachmentResponse(a domain.Attachment) attachmentResponse {
|
||||
return attachmentResponse{
|
||||
ID: a.ID.String(),
|
||||
ChatID: a.ChatID.String(),
|
||||
OwnerID: a.OwnerID.String(),
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: a.SHA256,
|
||||
Status: a.Status,
|
||||
Variants: []variantResponse{},
|
||||
ErrorCode: a.ErrorCode,
|
||||
CreatedAt: formatTime(a.CreatedAt),
|
||||
UpdatedAt: formatTime(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toIDStrings(ids []uuid.UUID) []string {
|
||||
result := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
result[i] = id.String()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] {
|
||||
items := make([]R, len(p.Items))
|
||||
for i, it := range p.Items {
|
||||
|
||||
@@ -43,6 +43,10 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "resource not found")
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", err.Error())
|
||||
case errors.Is(err, domain.ErrTooLarge):
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", err.Error())
|
||||
case errors.Is(err, domain.ErrUnsupportedMedia):
|
||||
writeError(w, http.StatusUnsupportedMediaType, "unsupported_media_type", err.Error())
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
|
||||
"method", r.Method, "path", r.URL.Path, "err", err)
|
||||
|
||||
@@ -12,18 +12,21 @@ import (
|
||||
type Pinger func(ctx context.Context) error
|
||||
|
||||
type Handler struct {
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
chats *service.ChatService
|
||||
messages *service.MessageService
|
||||
deps []Pinger
|
||||
log *slog.Logger
|
||||
draining atomic.Bool
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
chats *service.ChatService
|
||||
messages *service.MessageService
|
||||
attachments *service.AttachmentService
|
||||
deps []Pinger
|
||||
log *slog.Logger
|
||||
draining atomic.Bool
|
||||
}
|
||||
|
||||
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
|
||||
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
|
||||
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
|
||||
messages *service.MessageService, attachments *service.AttachmentService,
|
||||
deps []Pinger, log *slog.Logger) *Handler {
|
||||
return &Handler{users: users, auth: auth, chats: chats, messages: messages,
|
||||
attachments: attachments, deps: deps, log: log}
|
||||
}
|
||||
|
||||
func (h *Handler) StartDraining() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
"messenger/internal/handler"
|
||||
"messenger/internal/repository/postgres"
|
||||
"messenger/internal/repository/redis"
|
||||
@@ -22,6 +24,38 @@ import (
|
||||
"messenger/internal/service"
|
||||
)
|
||||
|
||||
type stubObjectStore struct {
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func newStubObjectStore() *stubObjectStore {
|
||||
return &stubObjectStore{objects: map[string][]byte{}}
|
||||
}
|
||||
|
||||
func (s *stubObjectStore) Put(_ context.Context, key string, r io.Reader, _ int64, _ string) error {
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.objects[key] = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubObjectStore) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
data, ok := s.objects[key]
|
||||
if !ok {
|
||||
return nil, domain.ErrNotFound
|
||||
}
|
||||
return io.NopCloser(strings.NewReader(string(data))), nil
|
||||
}
|
||||
|
||||
func (s *stubObjectStore) Delete(_ context.Context, key string) error {
|
||||
delete(s.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubObjectStore) Ping(context.Context) error { return nil }
|
||||
|
||||
func testURLs(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
|
||||
@@ -56,7 +90,8 @@ func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest
|
||||
auth := service.NewAuthService(store, sessions, ttl)
|
||||
chats := service.NewChatService(store)
|
||||
messages := service.NewMessageService(chats, store)
|
||||
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
|
||||
attachments := service.NewAttachmentService(chats, store, newStubObjectStore(), 10485760, 40000000)
|
||||
h := handler.New(users, auth, chats, messages, attachments, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
|
||||
srv := httptest.NewServer(router.New(h, "test"))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"uuid"
|
||||
)
|
||||
|
||||
const headerIdempotencyKey = "Idempotency-Key"
|
||||
@@ -29,7 +30,19 @@ func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
h.fail(w, r, badRequest("text is required"))
|
||||
return
|
||||
}
|
||||
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text)
|
||||
var attachmentIDs []uuid.UUID
|
||||
if req.AttachmentIDs != nil {
|
||||
attachmentIDs = make([]uuid.UUID, len(*req.AttachmentIDs))
|
||||
for i, raw := range *req.AttachmentIDs {
|
||||
id, ok := parseUUID(raw)
|
||||
if !ok {
|
||||
h.fail(w, r, badRequest("attachment_ids must contain UUIDs"))
|
||||
return
|
||||
}
|
||||
attachmentIDs[i] = id
|
||||
}
|
||||
}
|
||||
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text, attachmentIDs)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS message_attachments;
|
||||
DROP TABLE IF EXISTS attachments;
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_created_id_idx ON attachments (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
position int NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|
||||
@@ -200,6 +200,22 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, k
|
||||
if storedHash != requestHash {
|
||||
return domain.Message{}, domain.ErrConflict
|
||||
}
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, stored.ID)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
stored.AttachmentIDs, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (uuid.UUID, error) {
|
||||
var id uuid.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if stored.AttachmentIDs == nil {
|
||||
stored.AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
@@ -208,6 +224,20 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, k
|
||||
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if len(m.AttachmentIDs) > 0 {
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
SELECT $1, a.id, u.ord::int
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)
|
||||
JOIN attachments a ON a.id = u.id AND a.chat_id = $3 AND a.status = $4`,
|
||||
m.ID, m.AttachmentIDs, m.ChatID, domain.AttachmentReady)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if int(tag.RowsAffected()) != len(m.AttachmentIDs) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
@@ -247,9 +277,59 @@ func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domai
|
||||
if more {
|
||||
msgs = msgs[:limit]
|
||||
}
|
||||
if err := s.loadMessageAttachments(ctx, msgs); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return msgs, more, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a domain.Attachment) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.Status, a.ErrorCode, a.CreatedAt, a.UpdatedAt)
|
||||
return dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (domain.Attachment, error) {
|
||||
var a domain.Attachment
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at
|
||||
FROM attachments WHERE id = $1`, id,
|
||||
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
return a, dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) loadMessageAttachments(ctx context.Context, msgs []domain.Message) error {
|
||||
for i := range msgs {
|
||||
msgs[i].AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]uuid.UUID, len(msgs))
|
||||
index := make(map[uuid.UUID]int, len(msgs))
|
||||
for i, m := range msgs {
|
||||
ids[i] = m.ID
|
||||
index[m.ID] = i
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY($1) ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var messageID, attachmentID uuid.UUID
|
||||
if err := rows.Scan(&messageID, &attachmentID); err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
i := index[messageID]
|
||||
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, attachmentID)
|
||||
}
|
||||
return dbErr(rows.Err())
|
||||
}
|
||||
|
||||
func dbErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
region string
|
||||
}
|
||||
|
||||
func New(endpoint, region, accessKeyID, secretAccessKey, bucket string) (*Store, error) {
|
||||
host, secure := endpoint, false
|
||||
if parsed, err := url.Parse(endpoint); err == nil && parsed.Host != "" {
|
||||
host = parsed.Host
|
||||
secure = parsed.Scheme == "https"
|
||||
}
|
||||
client, err := minio.New(strings.TrimRight(host, "/"), &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Region: region,
|
||||
Secure: secure,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{client: client, bucket: bucket, region: region}, nil
|
||||
}
|
||||
|
||||
func (s *Store) EnsureBucket(ctx context.Context) error {
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return s.wrap(err)
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region}); err != nil {
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
|
||||
return nil
|
||||
}
|
||||
return s.wrap(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
_, err := s.client.BucketExists(ctx, s.bucket)
|
||||
return s.wrap(err)
|
||||
}
|
||||
|
||||
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType})
|
||||
if err != nil && minio.ToErrorResponse(err).Code == "NoSuchBucket" {
|
||||
if ensureErr := s.EnsureBucket(ctx); ensureErr == nil {
|
||||
_, err = s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType})
|
||||
}
|
||||
}
|
||||
return s.wrap(err)
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, s.wrap(err)
|
||||
}
|
||||
if _, err := object.Stat(); err != nil {
|
||||
object.Close()
|
||||
return nil, s.wrap(err)
|
||||
}
|
||||
return object, nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
return s.wrap(s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
|
||||
}
|
||||
|
||||
func (s *Store) wrap(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
if response.StatusCode == http.StatusNotFound {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -31,6 +31,9 @@ func New(h *handler.Handler, instanceID string) http.Handler {
|
||||
r.Get("/chats/{chat_id}", h.GetChat)
|
||||
r.Post("/chats/{chat_id}/messages", h.SendMessage)
|
||||
r.Get("/chats/{chat_id}/messages", h.ListMessages)
|
||||
r.Post("/chats/{chat_id}/attachments", h.UploadAttachment)
|
||||
r.Get("/attachments/{attachment_id}", h.GetAttachment)
|
||||
r.Get("/attachments/{attachment_id}/content", h.DownloadAttachment)
|
||||
})
|
||||
})
|
||||
return r
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
originalVariant = "original"
|
||||
maxFilenameRunes = 255
|
||||
sniffBytes = 512
|
||||
)
|
||||
|
||||
type AttachmentService struct {
|
||||
chats *ChatService
|
||||
repo AttachmentRepository
|
||||
store ObjectStore
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
}
|
||||
|
||||
func NewAttachmentService(chats *ChatService, repo AttachmentRepository, store ObjectStore, maxBytes, maxPixels int64) *AttachmentService {
|
||||
return &AttachmentService{chats: chats, repo: repo, store: store, maxBytes: maxBytes, maxPixels: maxPixels}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatID uuid.UUID, filename, contentType string, body io.Reader) (domain.Attachment, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkFilename(filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if contentType != domain.ContentPNG && contentType != domain.ContentJPEG {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: content type must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
raw, err := readLimited(body, s.maxBytes)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if detected := detectImageType(raw); detected != contentType {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: body does not match the declared image type", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if err := checkPixels(raw, s.maxPixels); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkIntegrity(raw); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
sum := sha256.Sum256(raw)
|
||||
createdAt := now()
|
||||
attachment := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: actor.ID,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(raw)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: "chats/" + chatID.String() + "/" + id.String(),
|
||||
Status: domain.AttachmentReady,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: createdAt,
|
||||
}
|
||||
if err := s.store.Put(ctx, attachment.ObjectKey, bytes.NewReader(raw), attachment.SizeBytes, contentType); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := s.repo.CreateAttachment(ctx, attachment); err != nil {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.Delete(cleanupCtx, attachment.ObjectKey)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(ctx context.Context, actor domain.User, id uuid.UUID) (domain.Attachment, error) {
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Open(ctx context.Context, actor domain.User, id uuid.UUID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if variant == "" {
|
||||
variant = originalVariant
|
||||
}
|
||||
if variant != originalVariant {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: only the original variant is available", domain.ErrInvalidInput)
|
||||
}
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is not ready", domain.ErrConflict)
|
||||
}
|
||||
content, err := s.store.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
return attachment, content, nil
|
||||
}
|
||||
|
||||
func checkFilename(filename string) error {
|
||||
if n := utf8.RuneCountInString(filename); n < 1 || n > maxFilenameRunes {
|
||||
return fmt.Errorf("%w: filename must be 1 to 255 characters", domain.ErrInvalidInput)
|
||||
}
|
||||
for _, r := range filename {
|
||||
if unicode.IsControl(r) || r == '/' || r == '\\' {
|
||||
return fmt.Errorf("%w: filename contains forbidden characters", domain.ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readLimited(body io.Reader, max int64) ([]byte, error) {
|
||||
raw, err := io.ReadAll(io.LimitReader(body, max+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: cannot read the upload body", domain.ErrInvalidInput)
|
||||
}
|
||||
if int64(len(raw)) > max {
|
||||
return nil, fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, max)
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil, fmt.Errorf("%w: upload body is empty", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func detectImageType(raw []byte) string {
|
||||
sniff := raw
|
||||
if len(sniff) > sniffBytes {
|
||||
sniff = sniff[:sniffBytes]
|
||||
}
|
||||
switch http.DetectContentType(sniff) {
|
||||
case domain.ContentPNG:
|
||||
return domain.ContentPNG
|
||||
case domain.ContentJPEG:
|
||||
return domain.ContentJPEG
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkPixels(raw []byte, max int64) error {
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: image header cannot be decoded", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 {
|
||||
return fmt.Errorf("%w: image has invalid dimensions", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if int64(config.Width) > max/int64(config.Height) {
|
||||
return fmt.Errorf("%w: image exceeds %d pixels", domain.ErrTooLarge, max)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkIntegrity(raw []byte) error {
|
||||
if _, _, err := image.Decode(bytes.NewReader(raw)); err != nil {
|
||||
return fmt.Errorf("%w: image is corrupted", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestCheckFilename(t *testing.T) {
|
||||
valid := []string{"photo.png", "фото 1.jpg", strings.Repeat("a", 255)}
|
||||
for _, name := range valid {
|
||||
if err := checkFilename(name); err != nil {
|
||||
t.Errorf("%q: unexpected error %v", name, err)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", strings.Repeat("a", 256), "dir/photo.png", `dir\photo.png`, "photo\x00.png", "photo\n.png", "photo\x7f.png"}
|
||||
for _, name := range invalid {
|
||||
if err := checkFilename(name); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("%q: got %v, want ErrInvalidInput", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectImageType(t *testing.T) {
|
||||
if got := detectImageType(encodePNG(t, 4, 4)); got != domain.ContentPNG {
|
||||
t.Errorf("png: got %q", got)
|
||||
}
|
||||
if got := detectImageType([]byte("not an image at all")); got != "" {
|
||||
t.Errorf("garbage: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPixels(t *testing.T) {
|
||||
if err := checkPixels(encodePNG(t, 320, 200), 40000000); err != nil {
|
||||
t.Errorf("small image: unexpected error %v", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(8000, 5000), 40000000); err != nil {
|
||||
t.Errorf("exact pixel limit: unexpected error %v", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(20000, 2001), 40000000); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("above pixel limit: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(65536, 65536), 40000000); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("huge dimensions: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if err := checkPixels([]byte("garbage"), 40000000); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("garbage: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckIntegrity(t *testing.T) {
|
||||
if err := checkIntegrity(encodePNG(t, 8, 8)); err != nil {
|
||||
t.Errorf("valid png: unexpected error %v", err)
|
||||
}
|
||||
corrupted := encodePNG(t, 8, 8)
|
||||
corrupted = corrupted[:len(corrupted)-20]
|
||||
if err := checkIntegrity(corrupted); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("truncated png: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMessageText(t *testing.T) {
|
||||
if err := checkMessageText("", false); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("empty text without attachments: got %v", err)
|
||||
}
|
||||
if err := checkMessageText(" ", false); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("blank text without attachments: got %v", err)
|
||||
}
|
||||
if err := checkMessageText("", true); err != nil {
|
||||
t.Errorf("empty text with attachments: unexpected error %v", err)
|
||||
}
|
||||
if err := checkMessageText(strings.Repeat("я", 4000), true); err != nil {
|
||||
t.Errorf("4000 characters: unexpected error %v", err)
|
||||
}
|
||||
if err := checkMessageText(strings.Repeat("я", 4001), true); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("4001 characters: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAttachmentIDs(t *testing.T) {
|
||||
ids := make([]uuid.UUID, 10)
|
||||
for i := range ids {
|
||||
ids[i] = uuid.New()
|
||||
}
|
||||
if err := checkAttachmentIDs(ids); err != nil {
|
||||
t.Errorf("ten unique ids: unexpected error %v", err)
|
||||
}
|
||||
if err := checkAttachmentIDs(append(ids, uuid.New())); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("eleven ids: got %v", err)
|
||||
}
|
||||
if err := checkAttachmentIDs([]uuid.UUID{ids[0], ids[0]}); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("duplicate ids: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHash(t *testing.T) {
|
||||
first, second := uuid.New(), uuid.New()
|
||||
if messageHash("", nil) != messageHash("", []uuid.UUID{}) {
|
||||
t.Error("absent attachment_ids must hash like an empty list")
|
||||
}
|
||||
if messageHash("hi", []uuid.UUID{first, second}) != messageHash("hi", []uuid.UUID{second, first}) {
|
||||
t.Error("attachment order must not change the hash")
|
||||
}
|
||||
if messageHash("hi", nil) == messageHash("hi!", nil) {
|
||||
t.Error("different text must change the hash")
|
||||
}
|
||||
if messageHash("hi", []uuid.UUID{first}) == messageHash("hi", []uuid.UUID{second}) {
|
||||
t.Error("different attachments must change the hash")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLimited(t *testing.T) {
|
||||
raw, err := readLimited(strings.NewReader("abcd"), 4)
|
||||
if err != nil || string(raw) != "abcd" {
|
||||
t.Fatalf("exact limit: got %q, %v", raw, err)
|
||||
}
|
||||
if _, err := readLimited(strings.NewReader("abcde"), 4); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("over limit: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if _, err := readLimited(strings.NewReader(""), 4); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("empty body: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func encodePNG(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
var buffer bytes.Buffer
|
||||
if err := png.Encode(&buffer, image.NewRGBA(image.Rect(0, 0, width, height))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func pngHeader(width, height uint32) []byte {
|
||||
var buffer bytes.Buffer
|
||||
buffer.WriteString("\x89PNG\r\n\x1a\n")
|
||||
header := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(header[0:4], width)
|
||||
binary.BigEndian.PutUint32(header[4:8], height)
|
||||
header[8], header[9] = 8, 2
|
||||
buffer.Write(binary.BigEndian.AppendUint32(nil, uint32(len(header))))
|
||||
buffer.WriteString("IHDR")
|
||||
buffer.Write(header)
|
||||
checksum := crc32.NewIEEE()
|
||||
checksum.Write([]byte("IHDR"))
|
||||
checksum.Write(header)
|
||||
buffer.Write(binary.BigEndian.AppendUint32(nil, checksum.Sum32()))
|
||||
return buffer.Bytes()
|
||||
}
|
||||
@@ -6,11 +6,16 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const maxMessageAttachments = 10
|
||||
|
||||
type MessageService struct {
|
||||
chats *ChatService
|
||||
messages MessageRepository
|
||||
@@ -20,22 +25,25 @@ func NewMessageService(chats *ChatService, messages MessageRepository) *MessageS
|
||||
return &MessageService{chats: chats, messages: messages}
|
||||
}
|
||||
|
||||
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string) (domain.Message, error) {
|
||||
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string, attachmentIDs []uuid.UUID) (domain.Message, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := checkText("text", text, 4000); err != nil {
|
||||
if err := checkMessageText(text, len(attachmentIDs) > 0); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := checkAttachmentIDs(attachmentIDs); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
m := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: actor.ID,
|
||||
Text: text,
|
||||
CreatedAt: now(),
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: actor.ID,
|
||||
Text: text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, hex.EncodeToString(sum[:]))
|
||||
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, messageHash(text, attachmentIDs))
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
return domain.Message{}, fmt.Errorf("%w: Idempotency-Key was already used with a different body", domain.ErrConflict)
|
||||
}
|
||||
@@ -63,3 +71,37 @@ func (s *MessageService) History(ctx context.Context, actor domain.User, chatID
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func checkMessageText(text string, hasAttachments bool) error {
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return fmt.Errorf("%w: text must be at most 4000 characters", domain.ErrInvalidInput)
|
||||
}
|
||||
if !hasAttachments && strings.TrimSpace(text) == "" {
|
||||
return fmt.Errorf("%w: text must not be empty without attachments", domain.ErrInvalidInput)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkAttachmentIDs(ids []uuid.UUID) error {
|
||||
if len(ids) > maxMessageAttachments {
|
||||
return fmt.Errorf("%w: attachment_ids must contain at most %d items", domain.ErrInvalidInput, maxMessageAttachments)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
return fmt.Errorf("%w: attachment_ids must not contain duplicates", domain.ErrInvalidInput)
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageHash(text string, ids []uuid.UUID) string {
|
||||
sorted := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
sorted[i] = id.String()
|
||||
}
|
||||
sort.Strings(sorted)
|
||||
sum := sha256.Sum256([]byte(text + "\n" + strings.Join(sorted, ",")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
@@ -25,6 +26,18 @@ type MessageRepository interface {
|
||||
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateAttachment(ctx context.Context, a domain.Attachment) error
|
||||
GetAttachment(ctx context.Context, id uuid.UUID) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
|
||||
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||
|
||||
Reference in New Issue
Block a user