2 changed files with 63 additions and 12 deletions
+28 -3
View File
@@ -25,6 +25,7 @@ type AttachmentService struct {
storage domain.ObjectStorage storage domain.ObjectStorage
maxBytes int64 maxBytes int64
maxPixels int64 maxPixels int64
decodeSem chan struct{}
} }
func NewAttachmentService( func NewAttachmentService(
@@ -39,6 +40,9 @@ func NewAttachmentService(
storage: storage, storage: storage,
maxBytes: maxBytes, maxBytes: maxBytes,
maxPixels: maxPixels, maxPixels: maxPixels,
// 40M pixels × 4 bytes (RGBA8) = 160 MB per full decode.
// API_MEMORY=256M → только один decode безопасен.
decodeSem: make(chan struct{}, 1),
} }
} }
@@ -81,7 +85,7 @@ func (s *AttachmentService) Upload(
if err != nil { if err != nil {
return nil, &domain.UnsupportedMediaTypeError{ return nil, &domain.UnsupportedMediaTypeError{
MediaType: contentType, MediaType: contentType,
Expected: "image/png или image/jpeg", Expected: "целостный image/png или image/jpeg",
} }
} }
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels { if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
@@ -91,6 +95,10 @@ func (s *AttachmentService) Upload(
} }
} }
if err := s.verifyIntegrity(ctx, buf, contentType); err != nil {
return nil, err
}
sha := sha256.Sum256(buf) sha := sha256.Sum256(buf)
id := uuid.NewString() id := uuid.NewString()
objectKey := "chats/" + chatID + "/" + id objectKey := "chats/" + chatID + "/" + id
@@ -127,6 +135,23 @@ func (s *AttachmentService) Upload(
return a, nil return a, nil
} }
func (s *AttachmentService) verifyIntegrity(ctx context.Context, buf []byte, contentType string) error {
select {
case s.decodeSem <- struct{}{}:
case <-ctx.Done():
return &domain.UnavailableError{Reason: "ожидание декодирования"}
}
defer func() { <-s.decodeSem }()
if _, _, err := image.Decode(bytes.NewReader(buf)); err != nil {
return &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "целостный " + contentType + " (без обрезки/повреждений)",
}
}
return nil
}
func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) { func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) {
a, err := s.attachments.GetByID(ctx, attachmentID) a, err := s.attachments.GetByID(ctx, attachmentID)
if err != nil { if err != nil {
@@ -166,8 +191,8 @@ func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID str
} }
func validateFilename(name string) error { func validateFilename(name string) error {
if name == "" { if strings.TrimSpace(name) == "" {
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым"} return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
} }
if utf8.RuneCountInString(name) > 255 { if utf8.RuneCountInString(name) > 255 {
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"} return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
+35 -9
View File
@@ -1,8 +1,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""10 параллельных ~10-MiB uploads; пик RAM api-реплик из cgroups v2 и docker stats."""
import concurrent.futures import concurrent.futures
import os
import struct
import subprocess import subprocess
import sys import sys
import time import time
import zlib
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
@@ -21,7 +25,6 @@ def api_containers():
def peak_kb(cid): def peak_kb(cid):
"""Peak memory из cgroups v2 в KB; None если недоступно."""
try: try:
out = subprocess.check_output( out = subprocess.check_output(
['docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak'], ['docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak'],
@@ -44,20 +47,43 @@ def current_mem_usage():
return '(docker stats недоступны)' return '(docker stats недоступны)'
def make_valid_png(target_bytes):
"""Валидный PNG ~target_bytes с шумом (level 0, без сжатия)."""
def chunk(typ, data):
return (struct.pack('>I', len(data)) + typ + data
+ struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff))
width = 1000
overhead = 8 + 25 + 12 + 12 # sig + IHDR + IDAThdr + IEND
target_raw = target_bytes - overhead - 16
height = max(1, target_raw // (1 + width * 3))
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
raw = bytearray()
for _ in range(height):
raw.append(0)
raw.extend(os.urandom(width * 3))
idat = zlib.compress(bytes(raw), 0)
return (b'\x89PNG\r\n\x1a\n'
+ chunk(b'IHDR', ihdr)
+ chunk(b'IDAT', idat)
+ chunk(b'IEND', b''))
def main(): def main():
args = arguments('RAM-эксперимент: 10 параллельных upload по 10 MiB') args = arguments('RAM-эксперимент: 10 параллельных upload по 10 MiB')
c = Client(args.base_url, args.ca_file, timeout=120) c = Client(args.base_url, args.ca_file, timeout=120)
alice, bob, eve, chat = c.bootstrap() alice, bob, eve, chat = c.bootstrap()
sample = (ROOT / 'tests/fixtures/sample.png').read_bytes() big = make_valid_png(MAX_UPLOAD - 50000)
big = (sample * 100)[:MAX_UPLOAD - 1] check(8_000_000 <= len(big) <= MAX_UPLOAD,
check(len(big) >= MAX_UPLOAD - 1024, 'fixture слишком маленький') f'PNG не в диапазоне: {len(big)}')
print(f'размер одного файла: {len(big)} байт (~{len(big) / 1024 / 1024:.1f} MiB)')
replicas = api_containers() replicas = api_containers()
check(len(replicas) >= 2, f'ожидалось >=2 api-реплики, найдено {len(replicas)}') check(len(replicas) >= 2, f'ожидалось >=2 api-реплики, найдено {len(replicas)}')
print(f'api-реплики: {[r[:12] for r in replicas]}')
print(f'api-реплики: {replicas}')
print(f'размер одного файла: {len(big)} байт (~{len(big) / 1024 / 1024:.1f} MiB)')
print() print()
print('--- memory.peak ДО ---') print('--- memory.peak ДО ---')
for cid in replicas: for cid in replicas:
@@ -115,9 +141,9 @@ def main():
f'{cid[:12]}: пик {p} KB > лимита {limit_mib * 1024} KB') f'{cid[:12]}: пик {p} KB > лимита {limit_mib * 1024} KB')
if any_measured: if any_measured:
print(f'PASS: 10 × 10 MiB uploads, пик RAM каждой реплики <= {limit_mib} MiB') print(f'PASS: 10 × ~10 MiB uploads, пик RAM каждой реплики <= {limit_mib} MiB')
else: else:
print('PASS: 10 × 10 MiB uploads (cgroups v2 peak недоступен, см. docker stats)') print('PASS: 10 × ~10 MiB uploads (cgroups v2 peak недоступен, см. docker stats)')
if __name__ == '__main__': if __name__ == '__main__':