lab 4 na 4

This commit is contained in:
2026-11-05 13:52:11 +03:00
parent 14166003b8
commit f6292ac308
48 changed files with 2255 additions and 183 deletions
+233
View File
@@ -0,0 +1,233 @@
package blobstore
import (
"bytes"
"context"
"errors"
"io"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
)
var ErrNotFound = errors.New("object not found")
type Store interface {
Put(ctx context.Context, key string, body io.ReadSeeker, 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
List(ctx context.Context, prefix string, fn func(key string, modified time.Time) error) error
Exists(ctx context.Context, key string) (bool, error)
}
type S3Config struct {
Endpoint, Region, Bucket, AccessKey, SecretKey string
}
type S3 struct {
client *s3.Client
bucket string
}
func NewS3(ctx context.Context, c S3Config) (*S3, error) {
if c.Endpoint == "" || c.Bucket == "" || c.AccessKey == "" || c.SecretKey == "" {
return nil, errors.New("incomplete S3 configuration")
}
cfg, err := config.LoadDefaultConfig(ctx,
config.WithRegion(c.Region),
config.WithRetryMaxAttempts(2),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, "")),
// Новые версии SDK по умолчанию добавляют контрольные суммы, которые не все S3-совместимые серверы понимают.
config.WithRequestChecksumCalculation(aws.RequestChecksumCalculationWhenRequired),
config.WithResponseChecksumValidation(aws.ResponseChecksumValidationWhenRequired),
)
if err != nil {
return nil, err
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(c.Endpoint)
o.UsePathStyle = true
})
return &S3{client: client, bucket: c.Bucket}, nil
}
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: body,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
return err
}
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
if isNotFound(err) {
return nil, ErrNotFound
}
return nil, err
}
return out.Body, nil
}
func (s *S3) Delete(ctx context.Context, key string) error {
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
return err
}
func (s *S3) Ping(ctx context.Context) error {
body := []byte("ok")
if _, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String("_health/probe"),
Body: bytes.NewReader(body),
ContentLength: aws.Int64(int64(len(body))),
}); err != nil {
return err
}
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String("_health/probe"),
})
if err != nil {
return err
}
defer out.Body.Close()
_, err = io.Copy(io.Discard, out.Body)
return err
}
func (s *S3) List(ctx context.Context, prefix string, fn func(key string, modified time.Time) error) error {
p := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{
Bucket: aws.String(s.bucket),
Prefix: aws.String(prefix),
})
for p.HasMorePages() {
page, err := p.NextPage(ctx)
if err != nil {
return err
}
for _, o := range page.Contents {
if err := fn(aws.ToString(o.Key), aws.ToTime(o.LastModified)); err != nil {
return err
}
}
}
return nil
}
func (s *S3) Exists(ctx context.Context, key string) (bool, error) {
_, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
if isNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func isNotFound(err error) bool {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NoSuchKey", "NotFound":
return true
}
}
return false
}
type Memory struct {
mu sync.Mutex
m map[string][]byte
mod map[string]time.Time
Err error
}
func NewMemory() *Memory { return &Memory{m: map[string][]byte{}, mod: map[string]time.Time{}} }
func (s *Memory) Put(_ context.Context, key string, body io.ReadSeeker, _ int64, _ string) error {
if s.Err != nil {
return s.Err
}
b, err := io.ReadAll(body)
if err != nil {
return err
}
s.mu.Lock()
s.m[key], s.mod[key] = b, time.Now()
s.mu.Unlock()
return nil
}
func (s *Memory) Get(_ context.Context, key string) (io.ReadCloser, error) {
if s.Err != nil {
return nil, s.Err
}
s.mu.Lock()
b, ok := s.m[key]
s.mu.Unlock()
if !ok {
return nil, ErrNotFound
}
return io.NopCloser(bytes.NewReader(b)), nil
}
func (s *Memory) Delete(_ context.Context, key string) error {
if s.Err != nil {
return s.Err
}
s.mu.Lock()
delete(s.m, key)
delete(s.mod, key)
s.mu.Unlock()
return nil
}
func (s *Memory) Ping(_ context.Context) error { return s.Err }
func (s *Memory) Exists(_ context.Context, key string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.m[key]
return ok, s.Err
}
func (s *Memory) List(_ context.Context, prefix string, fn func(string, time.Time) error) error {
s.mu.Lock()
keys := make([]string, 0, len(s.m))
for k := range s.m {
if strings.HasPrefix(k, prefix) {
keys = append(keys, k)
}
}
s.mu.Unlock()
for _, k := range keys {
if err := fn(k, s.mod[k]); err != nil {
return err
}
}
return nil
}
func (s *Memory) Len() int { s.mu.Lock(); defer s.mu.Unlock(); return len(s.m) }
+243
View File
@@ -0,0 +1,243 @@
package httpapi
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"mime"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"mtusi2026/internal/blobstore"
"mtusi2026/internal/idgen"
"mtusi2026/internal/model"
"mtusi2026/internal/store"
)
const (
maxAttachmentBytes = 10 << 20
maxPixels = 40_000_000
fullDecodePixels = 4_000_000 // полное декодирование только для небольших изображений
)
func validFilename(s string) bool {
n := utf8.RuneCountInString(s)
if n < 1 || n > 255 || strings.TrimSpace(s) == "" {
return false
}
for _, r := range s {
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
return false
}
}
return true
}
func (a *api) acquireUploadSlot(ctx context.Context) (func(), bool) {
t := time.NewTimer(5 * time.Second)
defer t.Stop()
select {
case a.uploadSem <- struct{}{}:
return func() { <-a.uploadSem }, true
case <-t.C:
return nil, false
case <-ctx.Done():
return nil, false
}
}
func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID, ok := uuidParam(w, r, requestID, "chat_id")
if !ok {
return
}
if a.blobs == nil {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
return
}
member, err := a.store.IsChatMember(r.Context(), chatID, u.ID)
if err != nil {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
return
}
if !member {
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
return
}
q := r.URL.Query()
filename := q.Get("filename")
if !q.Has("filename") || !validFilename(filename) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid filename")
return
}
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || (mt != "image/png" && mt != "image/jpeg") {
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "only image/png and image/jpeg are accepted")
return
}
if r.ContentLength > maxAttachmentBytes {
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
return
}
tmp, err := os.CreateTemp("", "upload-*")
if err != nil {
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
return
}
defer func() { tmp.Close(); os.Remove(tmp.Name()) }()
h := sha256.New()
n, err := io.Copy(io.MultiWriter(tmp, h), http.MaxBytesReader(w, r.Body, maxAttachmentBytes))
if err != nil {
var mbe *http.MaxBytesError
if errors.As(err, &mbe) {
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
} else {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "upload interrupted")
}
return
}
if n == 0 {
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "empty or invalid image")
return
}
release, ok := a.acquireUploadSlot(r.Context())
if !ok {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "upload capacity reached, retry later")
return
}
defer release()
head := make([]byte, 512)
hn, _ := tmp.ReadAt(head, 0)
if http.DetectContentType(head[:hn]) != mt {
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "content does not match declared type")
return
}
cfg, format, err := image.DecodeConfig(io.NewSectionReader(tmp, 0, n))
want := map[string]string{"image/png": "png", "image/jpeg": "jpeg"}[mt]
if err != nil || format != want || cfg.Width <= 0 || cfg.Height <= 0 {
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "invalid image")
return
}
pixels := int64(cfg.Width) * int64(cfg.Height)
if pixels > maxPixels {
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "image has too many pixels")
return
}
if pixels <= fullDecodePixels {
if _, _, err := image.Decode(io.NewSectionReader(tmp, 0, n)); err != nil {
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "corrupted image")
return
}
}
id := idgen.GenerateUUIDv4()
key := "attachments/" + chatID + "/" + id
baseCtx := context.WithoutCancel(r.Context())
putCtx, cancel := context.WithTimeout(baseCtx, 30*time.Second)
err = a.blobs.Put(putCtx, key, io.NewSectionReader(tmp, 0, n), n, mt)
cancel()
if err != nil {
log.Printf("s3 put failed: %v", err)
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
_ = a.blobs.Delete(delCtx, key)
delCancel()
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
return
}
dbCtx, dbCancel := context.WithTimeout(baseCtx, 10*time.Second)
defer dbCancel()
att, err := a.store.CreateAttachment(dbCtx, model.Attachment{
ID: id, ChatID: chatID, OwnerID: u.ID, Filename: filename, ContentType: mt,
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key,
})
if err != nil {
log.Printf("attachment metadata insert failed, compensating: %v", err)
if derr := a.blobs.Delete(dbCtx, key); derr != nil {
log.Printf("compensation delete failed (reconciler will clean up) key=%s: %v", key, derr)
}
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
return
}
writeJSON(w, http.StatusCreated, requestID, att)
}
func (a *api) loadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) (model.Attachment, bool) {
id, ok := uuidParam(w, r, requestID, "attachment_id")
if !ok {
return model.Attachment{}, false
}
att, err := a.store.GetAttachmentForUser(r.Context(), id, u.ID)
if err != nil {
if errors.Is(err, store.ErrAttachmentNotFound) {
writeError(w, http.StatusNotFound, requestID, codeNotFound, "attachment not found")
} else {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
}
return model.Attachment{}, false
}
return att, true
}
func (a *api) handleGetAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
att, ok := a.loadAttachment(w, r, u, requestID)
if !ok {
return
}
writeJSON(w, http.StatusOK, requestID, att)
}
func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
if q := r.URL.Query(); q.Has("variant") && q.Get("variant") != "original" {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "unknown variant")
return
}
att, ok := a.loadAttachment(w, r, u, requestID)
if !ok {
return
}
if a.blobs == nil {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
return
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
t := time.AfterFunc(8*time.Second, cancel)
body, err := a.blobs.Get(ctx, att.ObjectKey)
t.Stop()
if err != nil {
if errors.Is(err, blobstore.ErrNotFound) {
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
} else {
log.Printf("s3 get failed: %v", err)
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
}
return
}
defer body.Close()
w.Header().Set("Content-Type", att.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
w.Header().Set("X-Request-Id", requestID)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, body)
}
+34 -1
View File
@@ -3,18 +3,45 @@ package httpapi
import (
"context"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"mtusi2026/internal/blobstore"
)
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
}
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.Bool) http.HandlerFunc {
type blobProbe struct {
mu sync.Mutex
at time.Time
err error
st blobstore.Store
}
func (p *blobProbe) check(ctx context.Context) error {
p.mu.Lock()
defer p.mu.Unlock()
if time.Since(p.at) < time.Second {
return p.err
}
cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
p.err = p.st.Ping(cctx)
p.at = time.Now()
return p.err
}
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, blobs blobstore.Store, draining *atomic.Bool) http.HandlerFunc {
var probe *blobProbe
if blobs != nil {
probe = &blobProbe{st: blobs}
}
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
if draining.Load() {
@@ -34,6 +61,12 @@ func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.B
return
}
}
if probe != nil {
if err := probe.check(ctx); err != nil {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
return
}
}
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
}
}
+8 -6
View File
@@ -15,12 +15,14 @@ import (
type errorCode string
const (
codeInvalidRequest errorCode = "invalid_request"
codeUnauthorized errorCode = "unauthorized"
codeNotFound errorCode = "not_found"
codeConflict errorCode = "conflict"
codeUnavailable errorCode = "unavailable"
codeInternal errorCode = "internal_error"
codeInvalidRequest errorCode = "invalid_request"
codeUnauthorized errorCode = "unauthorized"
codeNotFound errorCode = "not_found"
codeConflict errorCode = "conflict"
codeUnavailable errorCode = "unavailable"
codeInternal errorCode = "internal_error"
codeTooLarge errorCode = "payload_too_large"
codeUnsupportedMedia errorCode = "unsupported_media_type"
)
func newRequestID() string {
+22 -4
View File
@@ -4,7 +4,9 @@ import (
"errors"
"net/http"
"regexp"
"strings"
"mtusi2026/internal/idgen"
"mtusi2026/internal/model"
"mtusi2026/internal/store"
)
@@ -12,7 +14,7 @@ import (
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID, ok := chatIDParam(w, r, requestID)
chatID, ok := uuidParam(w, r, requestID, "chat_id")
if !ok {
return
}
@@ -28,11 +30,27 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
return
}
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text)
ids := make([]string, 0, len(req.AttachmentIDs))
seen := map[string]bool{}
for _, id := range req.AttachmentIDs {
id = strings.ToLower(id)
if !idgen.IsValidUUID(id) || seen[id] {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid attachment_ids")
return
}
seen[id] = true
ids = append(ids, id)
}
if len(ids) > 10 || !store.ValidMessageBody(req.Text, len(ids) > 0) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text or attachment_ids")
return
}
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
if err != nil {
switch {
case errors.Is(err, store.ErrChatNotFound):
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat or attachment not found")
case errors.Is(err, store.ErrIdempotencyConflict):
writeError(w, http.StatusConflict, requestID, codeConflict, "Idempotency-Key was used with a different request body")
case errors.Is(err, store.ErrValidation):
+13 -1
View File
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"mtusi2026/internal/blobstore"
"mtusi2026/internal/cache"
"mtusi2026/internal/model"
"mtusi2026/internal/sessionstore"
@@ -17,6 +18,8 @@ type Options struct {
InstanceID string
Redis *redis.Client
Draining *atomic.Bool
Blobs blobstore.Store
MaxUploads int
}
func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler {
@@ -45,10 +48,16 @@ func NewRouterWithCache(
o.Draining = new(atomic.Bool)
}
if o.MaxUploads <= 0 {
o.MaxUploads = 4
}
a := &api{
store: s,
sessionStore: sessionStore,
chatCache: chatCache,
blobs: o.Blobs,
uploadSem: make(chan struct{}, o.MaxUploads),
}
apiMux := http.NewServeMux()
@@ -60,6 +69,9 @@ func NewRouterWithCache(
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", a.authMiddleware(a.handleUploadAttachment))
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", a.authMiddleware(a.handleGetAttachment))
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", a.authMiddleware(a.handleDownloadAttachment))
apiMux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(
func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
a.handleDeleteSession(w, r)
@@ -67,7 +79,7 @@ func NewRouterWithCache(
root := http.NewServeMux()
root.HandleFunc("GET /health/live", handleHealthLive)
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Draining))
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
var h http.Handler = root
+3
View File
@@ -9,6 +9,7 @@ import (
"golang.org/x/sync/singleflight"
"mtusi2026/internal/auth"
"mtusi2026/internal/blobstore"
"mtusi2026/internal/cache"
"mtusi2026/internal/model"
"mtusi2026/internal/sessionstore"
@@ -22,6 +23,8 @@ type api struct {
sessionStore sessionstore.Store
chatCache *cache.Cache
chatFlight singleflight.Group
blobs blobstore.Store
uploadSem chan struct{}
}
func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u model.User, requestID string)) http.HandlerFunc {
+9
View File
@@ -43,3 +43,12 @@ func chatIDParam(w http.ResponseWriter, r *http.Request, requestID string) (stri
}
return strings.ToLower(id), true
}
func uuidParam(w http.ResponseWriter, r *http.Request, requestID, name string) (string, bool) {
id := r.PathValue(name)
if !idgen.IsValidUUID(id) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid "+name)
return "", false
}
return strings.ToLower(id), true
}
+33 -6
View File
@@ -33,15 +33,17 @@ type ChatPage struct {
}
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type CreateMessageRequest struct {
Text string `json:"text"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessagePage struct {
@@ -63,3 +65,28 @@ type Session struct {
ExpiresAt time.Time `json:"expires_at"`
User User `json:"user"`
}
type Variant 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 Attachment 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 []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ObjectKey string `json:"-"`
}
+116
View File
@@ -0,0 +1,116 @@
package reconcile
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi2026/internal/blobstore"
)
type Report struct {
Scanned, Young, Orphans, Deleted, Missing int
}
type cand struct{ key string }
func Run(ctx context.Context, pool *pgxpool.Pool, blobs blobstore.Store, grace time.Duration,
dryRun, checkMissing bool, logf func(string, ...any)) (Report, error) {
var rep Report
cutoff := time.Now().Add(-grace)
var batch []string
flush := func() error {
if len(batch) == 0 {
return nil
}
rows, err := pool.Query(ctx, `SELECT object_key FROM attachments WHERE object_key = ANY($1)`, batch)
if err != nil {
return err
}
known := map[string]bool{}
for rows.Next() {
var k string
if err := rows.Scan(&k); err != nil {
rows.Close()
return err
}
known[k] = true
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, k := range batch {
if known[k] {
continue
}
rep.Orphans++
if dryRun {
logf("orphan (dry-run, not deleted): %s", k)
continue
}
if err := blobs.Delete(ctx, k); err != nil {
logf("orphan delete failed: %s: %v", k, err)
continue
}
rep.Deleted++
logf("orphan deleted: %s", k)
}
batch = batch[:0]
return nil
}
err := blobs.List(ctx, "attachments/", func(key string, modified time.Time) error {
rep.Scanned++
if modified.After(cutoff) {
rep.Young++
return nil
}
batch = append(batch, key)
if len(batch) >= 500 {
return flush()
}
return nil
})
if err != nil {
return rep, fmt.Errorf("list: %w", err)
}
if err := flush(); err != nil {
return rep, fmt.Errorf("check db: %w", err)
}
if checkMissing {
rows, err := pool.Query(ctx,
`SELECT id, object_key FROM attachments WHERE created_at < $1 ORDER BY created_at`, cutoff)
if err != nil {
return rep, err
}
type rec struct{ id, key string }
var recs []rec
for rows.Next() {
var r rec
if err := rows.Scan(&r.id, &r.key); err != nil {
rows.Close()
return rep, err
}
recs = append(recs, r)
}
rows.Close()
for _, r := range recs {
ok, err := blobs.Exists(ctx, r.key)
if err != nil {
logf("exists check failed: %s: %v", r.key, err)
continue
}
if !ok {
rep.Missing++
logf("MISSING object for attachment id=%s key=%s (metadata kept, needs manual decision)", r.id, r.key)
}
}
}
return rep, nil
}
+146 -26
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
@@ -21,10 +22,13 @@ import (
)
var (
ErrUsernameTaken = errors.New("username taken")
ErrChatNotFound = errors.New("chat not found or not accessible")
ErrValidation = errors.New("validation failed")
ErrCapacityExceeded = errors.New("message capacity exceeded")
ErrUsernameTaken = errors.New("username taken")
ErrChatNotFound = errors.New("chat not found or not accessible")
ErrValidation = errors.New("validation failed")
ErrCapacityExceeded = errors.New("message capacity exceeded")
ErrAttachmentNotFound = errors.New("attachment not found or not accessible")
ErrUsernameNotFound = errors.New("username not found")
ErrSessionNotFound = errors.New("session not found or expired")
)
type Store struct {
@@ -33,10 +37,102 @@ type Store struct {
chatSQLQueries atomic.Int64
}
func (s *Store) ResetChatSQLQueries() {
s.chatSQLQueries.Store(0)
}
func (s *Store) ChatSQLQueries() int64 {
return s.chatSQLQueries.Load()
}
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
var ok bool
err := s.pool.QueryRow(ctx,
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
chatID, userID).Scan(&ok)
return ok, err
}
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
err := s.pool.QueryRow(ctx,
`INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
RETURNING status, created_at, updated_at`,
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey,
).Scan(&a.Status, &a.CreatedAt, &a.UpdatedAt)
a.Variants = []model.Variant{}
return a, err
}
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID string) (model.Attachment, error) {
var a model.Attachment
err := s.pool.QueryRow(ctx,
`SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
a.object_key, a.status, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
WHERE a.id = $1`, id, userID,
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
&a.ObjectKey, &a.Status, &a.CreatedAt, &a.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return model.Attachment{}, ErrAttachmentNotFound
}
a.Variants = []model.Variant{}
return a, err
}
func (s *Store) loadAttachmentIDs(ctx context.Context, msgs []model.Message) error {
if len(msgs) == 0 {
return nil
}
ids := make([]string, len(msgs))
pos := make(map[string]int, len(msgs))
for i := range msgs {
ids[i] = msgs[i].ID
pos[msgs[i].ID] = i
msgs[i].AttachmentIDs = []string{}
}
rows, err := s.pool.Query(ctx,
`SELECT message_id, attachment_id FROM message_attachments
WHERE message_id IN (SELECT unnest($1::text[])::uuid)
ORDER BY message_id, position`, ids)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var mid, aid string
if err := rows.Scan(&mid, &aid); err != nil {
return err
}
if i, ok := pos[mid]; ok {
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, aid)
}
}
return rows.Err()
}
func New(pool *pgxpool.Pool, limiter *Limiter) *Store {
return &Store{pool: pool, Limiter: limiter}
}
func txAttachmentIDs(ctx context.Context, tx pgx.Tx, messageID string) ([]string, error) {
rows, err := tx.Query(ctx,
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, messageID)
if err != nil {
return nil, err
}
defer rows.Close()
ids := []string{}
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
var u model.User
err := s.pool.QueryRow(ctx,
@@ -238,12 +334,14 @@ func (s *Store) ListChatsForUser(ctx context.Context, userID, cursorStr string,
var ErrIdempotencyConflict = errors.New("idempotency key reused with different body")
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string) (model.Message, error) {
if !validMessageText(text) {
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string, attIDs []string) (model.Message, error) {
if attIDs == nil {
attIDs = []string{}
}
if !ValidMessageBody(text, len(attIDs) > 0) {
return model.Message{}, ErrValidation
}
sum := sha256.Sum256([]byte(text))
hash := hex.EncodeToString(sum[:])
hash := requestHash(text, attIDs)
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -261,6 +359,19 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
return model.Message{}, ErrChatNotFound
}
if len(attIDs) > 0 {
var n int
if err := tx.QueryRow(ctx,
`SELECT count(*) FROM attachments
WHERE chat_id = $1 AND id IN (SELECT unnest($2::text[])::uuid)`,
chatID, attIDs).Scan(&n); err != nil {
return model.Message{}, err
}
if n != len(attIDs) {
return model.Message{}, ErrAttachmentNotFound
}
}
msgID := idgen.GenerateUUIDv4()
tag, err := tx.Exec(ctx,
`INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
@@ -274,18 +385,20 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
if tag.RowsAffected() == 0 {
var storedHash string
var m model.Message
err := tx.QueryRow(ctx,
if err := tx.QueryRow(ctx,
`SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3`,
senderID, chatID, idemKey,
).Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
if err != nil {
).Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
return model.Message{}, err
}
if storedHash != hash {
return model.Message{}, ErrIdempotencyConflict
}
if m.AttachmentIDs, err = txAttachmentIDs(ctx, tx, m.ID); err != nil {
return model.Message{}, err
}
return m, nil
}
@@ -302,9 +415,17 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
}
return model.Message{}, err
}
for i, id := range attIDs {
if _, err := tx.Exec(ctx,
`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1,$2,$3)`,
m.ID, id, i); err != nil {
return model.Message{}, err
}
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, err
}
m.AttachmentIDs = attIDs
return m, nil
}
@@ -368,6 +489,9 @@ func (s *Store) ListMessages(ctx context.Context, chatID, userID, cursorStr stri
next = &nc
page = page[:limit]
}
if err := s.loadAttachmentIDs(ctx, page); err != nil {
return nil, nil, err
}
return page, next, nil
}
@@ -386,9 +510,8 @@ func isCheckViolation(err error) bool {
return errors.As(err, &pgErr) && pgErr.Code == "23514"
}
func validMessageText(s string) bool {
n := utf8.RuneCountInString(s)
if n == 0 || n > 4000 {
func ValidMessageBody(s string, hasAttachments bool) bool {
if utf8.RuneCountInString(s) > 4000 {
return false
}
hasContent := false
@@ -400,10 +523,17 @@ func validMessageText(s string) bool {
hasContent = true
}
}
return hasContent
return hasAttachments || hasContent
}
var ErrSessionNotFound = errors.New("session not found or expired")
func requestHash(text string, ids []string) string {
b, _ := json.Marshal(struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}{text, ids})
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, string, error) {
var u model.User
@@ -424,13 +554,3 @@ func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.U
return u, passwordHash, nil
}
var ErrUsernameNotFound = errors.New("username not found")
func (s *Store) ResetChatSQLQueries() {
s.chatSQLQueries.Store(0)
}
func (s *Store) ChatSQLQueries() int64 {
return s.chatSQLQueries.Load()
}