Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80965c5c03 | ||
|
|
727ea6efa0 |
@@ -25,6 +25,7 @@ type AttachmentService struct {
|
||||
storage domain.ObjectStorage
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
decodeSem chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
@@ -39,6 +40,9 @@ func NewAttachmentService(
|
||||
storage: storage,
|
||||
maxBytes: maxBytes,
|
||||
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 {
|
||||
return nil, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: contentType,
|
||||
Expected: "image/png или image/jpeg",
|
||||
Expected: "целостный image/png или image/jpeg",
|
||||
}
|
||||
}
|
||||
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)
|
||||
id := uuid.NewString()
|
||||
objectKey := "chats/" + chatID + "/" + id
|
||||
@@ -127,6 +135,23 @@ func (s *AttachmentService) Upload(
|
||||
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) {
|
||||
a, err := s.attachments.GetByID(ctx, attachmentID)
|
||||
if err != nil {
|
||||
@@ -166,8 +191,8 @@ func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID str
|
||||
}
|
||||
|
||||
func validateFilename(name string) error {
|
||||
if name == "" {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым"}
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
|
||||
}
|
||||
if utf8.RuneCountInString(name) > 255 {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""10 параллельных ~10-MiB uploads; пик RAM api-реплик из cgroups v2 и docker stats."""
|
||||
import concurrent.futures
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -21,7 +25,6 @@ def api_containers():
|
||||
|
||||
|
||||
def peak_kb(cid):
|
||||
"""Peak memory из cgroups v2 в KB; None если недоступно."""
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
['docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak'],
|
||||
@@ -44,20 +47,43 @@ def current_mem_usage():
|
||||
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():
|
||||
args = arguments('RAM-эксперимент: 10 параллельных upload по 10 MiB')
|
||||
c = Client(args.base_url, args.ca_file, timeout=120)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
sample = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
big = (sample * 100)[:MAX_UPLOAD - 1]
|
||||
check(len(big) >= MAX_UPLOAD - 1024, 'fixture слишком маленький')
|
||||
big = make_valid_png(MAX_UPLOAD - 50000)
|
||||
check(8_000_000 <= len(big) <= MAX_UPLOAD,
|
||||
f'PNG не в диапазоне: {len(big)}')
|
||||
print(f'размер одного файла: {len(big)} байт (~{len(big) / 1024 / 1024:.1f} MiB)')
|
||||
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, f'ожидалось >=2 api-реплики, найдено {len(replicas)}')
|
||||
|
||||
print(f'api-реплики: {replicas}')
|
||||
print(f'размер одного файла: {len(big)} байт (~{len(big) / 1024 / 1024:.1f} MiB)')
|
||||
print(f'api-реплики: {[r[:12] for r in replicas]}')
|
||||
print()
|
||||
print('--- memory.peak ДО ---')
|
||||
for cid in replicas:
|
||||
@@ -115,9 +141,9 @@ def main():
|
||||
f'{cid[:12]}: пик {p} KB > лимита {limit_mib * 1024} KB')
|
||||
|
||||
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:
|
||||
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__':
|
||||
|
||||
Reference in New Issue
Block a user