feat(storage): add RustFS attachments and presigned uploads

Add two API replicas, safe object reconciliation, upload validation, regression tests and documented load experiments.
This commit is contained in:
2026-11-12 10:16:39 +03:00
parent ec540a1a72
commit dc46ac213d
118 changed files with 44628 additions and 38 deletions
+160
View File
@@ -0,0 +1,160 @@
"""Integration checks against the local Compose stack. --lifecycle restarts its services."""
import argparse
import base64
import json
from pathlib import Path
import struct
import subprocess
import sys
import time
import uuid
from urllib.parse import quote
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, run
def compose(*args):
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT, capture_output=True, text=True)
check(result.returncode == 0, 'Compose action failed: ' + ' '.join(args[:2]))
return result.stdout.strip()
def wait_ready(client):
deadline = time.monotonic() + 90
observed = set()
stable_since = None
while time.monotonic() < deadline:
try:
response = client.call('GET', '/health/ready', schema='Health')
upstreams = compose('exec', '-T', 'nginx', 'cat', '/etc/nginx/ready-upstreams.conf')
# A single 200 can come from an old Nginx worker while a removal
# reload is still pending. Wait for both re-added replicas to settle.
check(sum(':8080' in line for line in upstreams.splitlines()) == 2,
'Both upstreams have not recovered')
observed.add(response['headers']['X-Instance-Id'])
if stable_since is None:
stable_since = time.monotonic()
if len(observed) == 2 and time.monotonic() - stable_since >= 4:
return
except Failure:
observed.clear()
stable_since = None
time.sleep(1)
raise Failure('API did not recover')
def direct_call(method, path, expected, actor=None, raw=None, content_type=None):
"""Probe the API process when the LB has excluded every unready replica."""
headers = {'Authorization': 'Bearer ' + actor['token']} if actor else {}
if content_type:
headers['Content-Type'] = content_type
request = {'method': method, 'path': path, 'headers': headers,
'body': base64.b64encode(raw).decode() if raw is not None else None}
script = """const q=JSON.parse(require('node:fs').readFileSync(0,'utf8'));
fetch('http://127.0.0.1:8080'+q.path,{method:q.method,headers:q.headers,
body:q.body===null?undefined:Buffer.from(q.body,'base64')}).then(async r=>{
console.log(JSON.stringify({status:r.status,body:await r.json(),
requestId:r.headers.get('x-request-id'),instanceId:r.headers.get('x-instance-id')}));
}).catch(()=>process.exit(1));"""
result = subprocess.run(['docker', 'compose', 'exec', '-T', '--index', '1',
'api', 'node', '-e', script], cwd=ROOT,
input=json.dumps(request), capture_output=True, text=True)
check(result.returncode == 0, 'direct API probe failed')
response = json.loads(result.stdout)
check(response['status'] == expected, 'direct API returned wrong status')
check(response['requestId'] and response['instanceId'], 'direct API lacks response identifiers')
if expected >= 400:
check(response['body']['error']['request_id'] == response['requestId'], 'error request ID differs')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--lifecycle', action='store_true')
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
def upload(data=png, name='фото.png', mime='image/png', expected=201, actor=alice):
return c.call('POST', path + '/attachments?filename=' + quote(name, safe=''), expected,
actor=actor, raw=data, headers={'Content-Type': mime},
schema='Attachment' if expected == 201 else None)
att = upload()['json']
item = '/api/v1/attachments/' + att['id']
check(c.call('GET', item, actor=bob, schema='Attachment')['json'] == att, 'metadata differs')
check(c.call('GET', item + '/content', actor=bob)['bytes'] == png, 'PNG changed')
c.call('GET', item + '/content?variant=thumbnail', 404, actor=bob)
c.call('GET', item, 401)
c.call('GET', item, 404, actor=eve)
c.call('GET', item + '/content', 404, actor=eve)
upload(actor=eve, expected=404)
upload(name='../photo.png', expected=400)
upload(name='photo\\bad.png', expected=400)
upload(name='bad\x00.png', expected=400)
upload(name=' ', expected=400)
upload(data=b'not an image', expected=415)
upload(data=png[:50], expected=415)
upload(mime='image/jpeg', expected=415)
upload(data=b'x' * (10485760 + 1), expected=413)
def chunk(kind, value):
return struct.pack('>I', len(value)) + kind + value + struct.pack('>I', zlib.crc32(kind + value))
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0))
huge += chunk(b'IDAT', zlib.compress(b'\x00\x00\x00\x00')) + chunk(b'IEND', b'')
upload(data=huge, expected=413)
jpeg = subprocess.run(['node', '-e',
"require('sharp')('tests/fixtures/sample.png').jpeg().toBuffer().then(b=>process.stdout.write(b))"],
cwd=ROOT, capture_output=True, check=True).stdout
jpg = upload(data=jpeg, name='photo.jpg', mime='image/jpeg')['json']
check(c.call('GET', '/api/v1/attachments/' + jpg['id'] + '/content', actor=bob)['bytes'] == jpeg, 'JPEG changed')
key = uuid.uuid4().hex
message = c.message(alice, chat, '', key, [att['id']])['json']
check(c.message(alice, chat, '', key, [att['id']])['json'] == message, 'replay differs')
c.call('POST', path + '/messages', 409, actor=alice, body={'text': '', 'attachment_ids': [jpg['id']]}, headers={'Idempotency-Key': key})
for ids, status in (([att['id'], att['id']], 400), ([str(uuid.uuid4())], 404), (None, 400)):
c.call('POST', path + '/messages', status, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Other chat', 'member_ids': [alice['id']]}, schema='Chat')['json']
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
if args.lifecycle:
anonymous_url = 'http://s3:9000/messenger-attachments/originals/' + chat['id'] + '/' + att['id']
status = compose('exec', '-T', 'api', 'node', '-e',
'fetch(process.argv[1]).then(r=>console.log(r.status))', anonymous_url)
check(status == '403', 'S3 object is publicly readable')
try:
compose('stop', 's3')
direct_call('GET', '/health/ready', 503)
direct_call('GET', item, 200, actor=bob)
direct_call('GET', item + '/content', 503, actor=bob)
direct_call('POST', path + '/attachments?filename=outage.png', 503,
actor=alice, raw=png, content_type='image/png')
deadline = time.monotonic() + 15
while True:
upstreams = compose('exec', '-T', 'nginx', 'cat', '/etc/nginx/ready-upstreams.conf')
if ':8080' not in upstreams:
break
check(time.monotonic() < deadline, 'Nginx still routes to unready replicas')
time.sleep(0.5)
finally:
compose('start', 's3')
wait_ready(c)
check(c.call('GET', item + '/content', actor=bob)['bytes'] == png, 'original lost after storage recovery')
compose('stop')
compose('up', '-d', '--wait', '--wait-timeout', '180')
wait_ready(c)
check(c.call('GET', item + '/content', actor=bob)['bytes'] == png, 'original lost after stack restart')
check(c.message(alice, chat, '', key, [att['id']])['json'] == message, 'message lost after restart')
print('PASS: attachments, validation, ACL, idempotency' + (', private S3, outage and persistence' if args.lifecycle else ''))
if __name__ == '__main__':
run(main)
+77
View File
@@ -0,0 +1,77 @@
// Remove only fixtures belonging to this one concurrency run, using restricted API keys.
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
const require = createRequire(`${process.cwd()}/package.json`);
const { PrismaService } = require('./dist/prisma/prisma.service.js');
const { StorageService } = require('./dist/Storage/storage.service.js');
const {
tryAttachmentObjectLock,
OBJECT_TRANSACTION,
} = require('./dist/Attachment/object-lock.js');
let input = '';
for await (const part of process.stdin) input += part;
const {
runId,
chatId,
chatIds = chatId ? [chatId] : [],
userIds,
kind = 'concurrency',
} = JSON.parse(input);
assert.ok(
['concurrency', 'upload-interruption', 'direct-upload'].includes(kind),
);
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
assert.match(runId, uuid);
assert.ok(Array.isArray(userIds) && userIds.length <= 2);
for (const id of userIds) assert.match(id, uuid);
if (chatId) assert.match(chatId, uuid);
assert.ok(
Array.isArray(chatIds) &&
chatIds.length <= 3 &&
new Set(chatIds).size === chatIds.length,
);
for (const value of chatIds) assert.match(value, uuid);
const db = new PrismaService();
const storage = new StorageService();
try {
await db.onModuleInit();
const users = await db.user.findMany({ where: { id: { in: userIds } } });
assert.ok(
users.every((user) => user.username.startsWith(`u_cu${runId.slice(0, 8)}`)),
);
for (const chatId of chatIds) {
const chat = await db.chat.findUnique({
where: { id: chatId },
include: { members: true },
});
assert.equal(chat?.title, `${kind}:${runId}`);
assert.ok(chat.members.every((member) => userIds.includes(member.userId)));
const directUploads = await db.directUpload.findMany({ where: { chatId } });
for (const upload of directUploads) {
assert.ok(userIds.includes(upload.ownerId));
await storage.remove(`staging/${chatId}/${upload.id}`);
}
await db.directUpload.deleteMany({ where: { chatId } });
const attachments = await db.attachment.findMany({ where: { chatId } });
for (const attachment of attachments) {
assert.ok(userIds.includes(attachment.ownerId));
assert.equal(
attachment.objectKey,
`originals/${chatId}/${attachment.id}`,
);
await db.$transaction(async (tx) => {
assert.ok(await tryAttachmentObjectLock(tx, attachment.objectKey));
await storage.remove(attachment.objectKey);
await tx.attachment.delete({ where: { id: attachment.id } });
}, OBJECT_TRANSACTION);
}
await db.chat.delete({ where: { id: chatId } });
}
await db.user.deleteMany({
where: { id: { in: users.map((user) => user.id) } },
});
console.log('PASS: concurrency fixtures removed');
} finally {
storage.onModuleDestroy();
await db.onModuleDestroy();
}
+281
View File
@@ -0,0 +1,281 @@
"""Concurrent raw PNG uploads through Nginx with per-API RSS measurements. Python 3.9+."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import hashlib
import http.client
import json
from pathlib import Path
from queue import Queue, Empty
import random
import ssl
import struct
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, shape
class UploadFailure(Failure):
def __init__(self, response):
super().__init__(f'Concurrent upload returned {response.status}, expected 201')
self.details = {'status': response.status,
'instance': response.getheader('X-Instance-Id'),
'requestId': response.getheader('X-Request-Id')}
def docker(*args, **kwargs):
return subprocess.run(['docker', *args], cwd=ROOT, capture_output=True,
text=True, check=True, timeout=90, **kwargs).stdout
class MemoryProbe:
def __init__(self, container):
self.container = container
self.messages = Queue()
source = (ROOT / 'test/upload-memory-probe.mjs').read_text(encoding='utf-8')
self.process = subprocess.Popen(
['docker', 'exec', '-i', container, 'node', '--input-type=module', '-e', source],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, bufsize=1,
)
threading.Thread(target=self.read, daemon=True).start()
def read(self):
try:
for line in self.process.stdout:
self.messages.put(json.loads(line))
except (ValueError, OSError):
self.messages.put({'event': 'error'})
finally:
self.messages.put({'event': 'closed'})
def receive(self, expected):
try:
value = self.messages.get(timeout=45)
except Empty:
raise Failure('API memory probe timed out') from None
check(value.get('event') == expected, 'API memory probe failed: ' + value.get('event', 'unknown'))
return value
def command(self, command, response):
self.process.stdin.write(command + '\n')
self.process.stdin.flush()
return self.receive(response)
def close(self):
if self.process.poll() is None:
try:
self.process.stdin.write('quit\n')
self.process.stdin.flush()
self.process.stdin.close()
self.process.wait(timeout=15)
except (OSError, subprocess.TimeoutExpired):
self.process.kill()
self.process.wait(timeout=10)
self.process.stdout.close()
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
def png_image(side):
# Deterministic noise is poorly compressible: the encoded file really occupies RAM.
rng = random.Random(side)
rows = b''.join(b'\0' + rng.randbytes(side * 3) for _ in range(side))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', side, side, 8, 2, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(rows, level=1)))
def upload(base, actor, chat, body, filename, gate, duration, timeout):
target = urlsplit(base + '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename)
connection_type = http.client.HTTPSConnection if target.scheme == 'https' else http.client.HTTPConnection
kwargs = {'context': ssl.create_default_context()} if target.scheme == 'https' else {}
connection = connection_type(target.hostname, target.port, timeout=timeout, **kwargs)
try:
connection.putrequest('POST', target.path + '?' + target.query)
connection.putheader('Authorization', 'Bearer ' + actor['token'])
connection.putheader('Content-Type', 'image/png')
connection.putheader('Content-Length', str(len(body)))
connection.endheaders()
first = min(65536, len(body) - 1)
connection.send(body[:first])
# Every connection has sent headers and an incomplete body before any may finish.
gate.wait(timeout=timeout)
started = time.monotonic()
for offset in range(first, len(body), 65536):
end = min(offset + 65536, len(body))
deadline = started + duration * (end - first) / (len(body) - first)
time.sleep(max(0, deadline - time.monotonic()))
connection.send(body[offset:end])
response = connection.getresponse()
data = response.read(1024 * 1024 + 1)
if response.status != 201:
raise UploadFailure(response)
check(len(data) <= 1024 * 1024, 'Upload response unexpectedly large')
check(response.getheader('Content-Type', '').startswith('application/json'), 'Upload response is not JSON')
check(response.getheader('X-Request-Id'), 'Upload lacks request identifier')
instance = response.getheader('X-Instance-Id')
check(instance, 'Upload lacks instance identifier')
attachment = shape(json.loads(data), 'Attachment')
check(attachment['status'] == 'ready', 'Concurrent attachment is not ready')
check(attachment['chat_id'] == chat['id'] and attachment['owner_id'] == actor['id'], 'Incorrect attachment ownership')
check(attachment['filename'] == filename and attachment['content_type'] == 'image/png', 'Incorrect attachment metadata')
digest = hashlib.sha256(body).hexdigest()
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(body), 'Upload bytes/metadata mismatch')
return {'attachment': attachment, 'instance': instance, 'elapsedSeconds': time.monotonic() - started,
'sha256': digest, 'sizeBytes': len(body)}
except BaseException:
gate.abort()
raise
finally:
connection.close()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--concurrency', type=int, default=10)
parser.add_argument('--rounds', type=int, default=2)
parser.add_argument('--sizes', type=int, nargs='+', default=[512, 1792], metavar='SIDE_PX')
parser.add_argument('--upload-seconds', type=float, default=2)
parser.add_argument('--timeout', type=float, default=60)
parser.add_argument('--max-rss-mib', type=float, help='Optional assertion budget per API process, not a container resource limit')
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/concurrent-uploads.json')
args = parser.parse_args()
check(10 <= args.concurrency <= 64, '--concurrency must be between 10 and 64')
check(1 <= args.rounds <= 10, '--rounds must be between 1 and 10')
check(all(64 <= side <= 1800 for side in args.sizes), '--sizes must be between 64 and 1800 pixels')
check(0.5 <= args.upload_seconds <= 10 and args.timeout > args.upload_seconds + 5, 'Invalid upload timing')
check(args.max_rss_mib is None or args.max_rss_mib > 0, 'RSS budget must be positive')
client = Client(args.base_url, timeout=args.timeout)
client.call('GET', '/health/ready', schema='Health')
run_id = str(uuid.uuid4())
report = {'status': 'running', 'startedAt': datetime.now(timezone.utc).isoformat(),
'concurrency': args.concurrency, 'roundsPerSize': args.rounds,
'uploadSeconds': args.upload_seconds, 'maxRssMiB': args.max_rss_mib,
'memoryMethod': 'API /proc VmRSS sampled every 50 ms; VmHWM is lifetime, not reset; probe RSS excluded',
'waves': []}
actors, probes, chat = [], [], None
try:
containers = docker('compose', 'ps', '-q', 'api').split()
check(len(containers) >= 2, 'Expected at least two running API replicas')
before = {state['Id']: (state['State']['StartedAt'], state['RestartCount'])
for state in json.loads(docker('inspect', *containers))}
for container in containers:
probe = MemoryProbe(container)
probes.append(probe)
probe.ready = probe.receive('ready')
owner = client.user('cu' + run_id[:8] + 'a')
actors.append(owner)
reader = client.user('cu' + run_id[:8] + 'b')
actors.append(reader)
chat = client.call('POST', '/api/v1/chats', 201, actor=owner,
body={'title': 'concurrency:' + run_id, 'member_ids': [actor['id'] for actor in actors]},
schema='Chat')['json']
for side in args.sizes:
image = png_image(side)
for number in range(1, args.rounds + 1):
bodies = [image + chunk(b'tEXt', f'fixture\0{run_id}-{side}-{number}-{i}'.encode()) + chunk(b'IEND', b'')
for i in range(args.concurrency)]
check(all(len(body) <= 10485760 for body in bodies), 'Generated PNG exceeds 10 MiB')
wave = {'sidePixels': side, 'round': number, 'fileBytes': len(bodies[0]),
'totalBytes': sum(map(len, bodies)), 'incompleteUploadsAtBarrier': 0,
'successfulUploads': 0, 'verifiedDownloads': 0, 'memory': []}
report['waves'].append(wave)
for probe in probes:
probe.command('begin', 'begin')
gate = threading.Barrier(args.concurrency + 1)
started = time.monotonic()
futures = []
print(f'Uploading: {args.concurrency} x {len(bodies[0]) / 1048576:.2f} MiB, round {number}', flush=True)
try:
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(upload, client.base, owner, chat, body,
f'{side}-{number}-{i}.png', gate, args.upload_seconds, args.timeout)
for i, body in enumerate(bodies)]
gate.wait(timeout=args.timeout)
wave['incompleteUploadsAtBarrier'] = args.concurrency
results = [future.result() for future in futures]
finally:
wave['uploadWallSeconds'] = time.monotonic() - started
memory = [{'instance': probe.ready['instance'], **probe.command('end', 'summary')} for probe in probes]
wave['memory'] = memory
wave['successfulUploads'] = sum(future.done() and not future.cancelled() and future.exception() is None for future in futures)
wave['failedUploads'] = [
{'index': index, 'errorType': type(future.exception()).__name__,
**getattr(future.exception(), 'details', {})}
for index, future in enumerate(futures)
if future.done() and not future.cancelled() and future.exception() is not None
]
wave['instances'] = {name: sum(r['instance'] == name for r in results) for name in sorted({r['instance'] for r in results})}
wave['latencySeconds'] = {'min': min(r['elapsedSeconds'] for r in results), 'max': max(r['elapsedSeconds'] for r in results)}
check(len({r['attachment']['id'] for r in results}) == args.concurrency, 'Attachment IDs collide')
check(len(wave['instances']) >= 2, 'Concurrent uploads did not reach both replicas')
check(set(wave['instances']).issubset({probe.ready['instance'] for probe in probes}), 'Unmeasured API replica served uploads')
for sample in memory:
check(sample['samples'] >= 2, 'Insufficient memory samples during upload')
check(sample['oomDelta'] == 0 and sample['oomKillDelta'] == 0, 'API cgroup reported OOM during upload')
if args.max_rss_mib is not None:
check(sample['sampledPeakRssBytes'] <= args.max_rss_mib * 1048576, 'API sampled RSS exceeded assertion budget')
for result in results:
path = '/api/v1/attachments/' + result['attachment']['id']
meta = client.call('GET', path, actor=reader, schema='Attachment')['json']
check(meta == result['attachment'], 'Concurrent metadata changed')
data = client.call('GET', path + '/content', actor=reader)['bytes']
check(len(data) == result['sizeBytes'] and hashlib.sha256(data).hexdigest() == result['sha256'], 'Concurrent download checksum mismatch')
wave['verifiedDownloads'] += 1
peaks = ', '.join(f"{s['instance']}: {s['sampledPeakRssBytes'] / 1048576:.1f} MiB" for s in memory)
print('PASS: all uploads/downloads verified; sampled API RSS peaks: ' + peaks, flush=True)
after = json.loads(docker('inspect', *containers))
check(all(before[state['Id']] == (state['State']['StartedAt'], state['RestartCount'])
and state['State']['Running'] and not state['State']['OOMKilled'] for state in after), 'API restarted or was OOM-killed')
client.call('GET', '/health/ready', schema='Health')
report['status'] = 'passed'
except BaseException as error:
report['status'] = 'failed'
report['errorType'] = type(error).__name__
if isinstance(error, Failure):
report['failure'] = str(error)
raise
finally:
for probe in probes:
if hasattr(probe, 'process'):
try:
probe.close()
except (OSError, subprocess.SubprocessError):
report['probeCloseFailed'] = True
try:
source = (ROOT / 'test/concurrent-cleanup.mjs').read_text(encoding='utf-8')
payload = json.dumps({'runId': run_id, 'chatId': chat['id'] if chat else None,
'userIds': [actor['id'] for actor in actors]})
docker('compose', 'exec', '-T', '--index', '1', 'api', 'node', '--input-type=module', '-e', source, input=payload)
report['fixturesRemoved'] = True
except BaseException:
report['fixturesRemoved'] = False
if report['status'] == 'passed':
report['status'] = 'failed'
raise Failure('Concurrent fixtures cleanup failed') from None
finally:
report['finishedAt'] = datetime.now(timezone.utc).isoformat()
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('PASS: concurrent uploads, byte integrity, memory sampling and no API restarts/OOM', flush=True)
print('Report: ' + str(args.output))
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError, threading.BrokenBarrierError) as error:
# Never include subprocess arguments or request headers: they can contain credentials.
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+167
View File
@@ -0,0 +1,167 @@
"""Compare the entire proxy/direct upload workflows, including complete validation."""
import argparse
import importlib.util
import datetime
import json
import subprocess
import sys
import time
from direct_client import ROOT, Client, Failure, check, docker, fixture, grant, put, complete, verify
spec = importlib.util.spec_from_file_location('upload_metrics', ROOT / 'test/concurrent-uploads.py')
metrics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(metrics)
def collect_profiles(case, since, repeats):
records = {}
for line in docker('compose', 'logs', '--no-color', '--since', since, 'api').splitlines():
if 'UPLOAD_MEMORY_PROFILE ' in line:
record = json.loads(line.split('UPLOAD_MEMORY_PROFILE ', 1)[1])
records[record['requestId']] = record
case['profiles'] = [records[request_id] for request_id in case['requestIds'] if request_id in records]
check(len(case['profiles']) == repeats, 'Missing opt-in API stage profiles')
for record in case['profiles']:
check(record['mode'] == case['mode'] and record['status'] == 201 and record['finished'], 'Invalid stage profile')
names = {stage['name'] for stage in record['stages']}
check({'sharp_metadata', 'sharp_decode_stats', 'serialize_response'} <= names, 'Async stage context was lost')
if case['mode'] == 'direct':
check({'s3_stream_sha256_to_file', 'sha256_finalize', 's3_copy'} <= names, 'Missing direct profile stages')
def restart_api(client, containers):
def states():
return docker('inspect', '--format', '{{.State.Health.Status}} {{.State.StartedAt}}', *containers).splitlines()
before = states()
docker('compose', 'restart', 'api')
deadline = time.monotonic() + 120
routed = set()
while time.monotonic() < deadline:
current = states()
if len(current) == 2 and all(line.startswith('healthy ') for line in current):
check(all(old != new for old, new in zip(before, current)), 'API did not restart')
try:
response = client.call('GET', '/health/ready')
routed.add(response['headers']['X-Instance-Id'])
if len(routed) == 2:
return current
except Failure:
pass
time.sleep(1)
raise Failure('API did not become ready after restart')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--sizes', type=int, nargs='+', default=[512, 1792])
parser.add_argument('--repeats', type=int, default=3)
parser.add_argument('--restart-api', action='store_true', help='Restart both API replicas before each measured case')
parser.add_argument('--rounds', type=int, default=1, help='Reverse workflow order on alternate rounds')
parser.add_argument('--profile', action='store_true', help='Collect opt-in API stage profiles and RSS after a five-second idle period')
args = parser.parse_args()
check(len(set(args.sizes)) >= 2 and all(64 <= side <= 1800 for side in args.sizes), 'Choose at least two image sides between 64 and 1800')
check(1 <= args.repeats <= 10, 'Repeats must be between 1 and 10')
check(1 <= args.rounds <= 5, 'Rounds must be between 1 and 5')
warmups = 4 if args.restart_api else 1
report = {'status': 'failed', 'repeats': args.repeats, 'rounds': args.rounds,
'restartApiBeforeCase': args.restart_api, 'warmupUploadsPerCase': warmups, 'cases': [],
'method': 'One upload at a time; measured direct flow includes grant, PUT, and complete with full image validation. Download verification is outside the measurement window. RSS sampling 50 ms; network counters sum non-loopback API interfaces, including DB/S3/background health traffic. Probe RSS excluded.'}
probes = []
log_start = datetime.datetime.now(datetime.timezone.utc).isoformat()
try:
readiness = Client('http://127.0.0.1:8080', timeout=5)
deadline = time.monotonic() + 90
routed = set()
while time.monotonic() < deadline:
try:
routed.add(readiness.call('GET', '/health/ready')['headers']['X-Instance-Id'])
if len(routed) == 2: break
except Failure:
pass
time.sleep(1)
check(len(routed) == 2, 'Both API replicas must be ready through Nginx')
with fixture() as (client, owner, reader, chat, _):
containers = docker('compose', 'ps', '-q', 'api').split()
check(len(containers) == 2, 'Expected two API replicas')
cases = [(round_index + 1, side, mode) for round_index in range(args.rounds)
for side in args.sizes
for mode in (['proxy', 'direct'] if round_index % 2 == 0 else ['direct', 'proxy'])]
for round_number, side, mode in cases:
image = metrics.png_image(side) + metrics.chunk(b'IEND', b'')
for probe in probes: probe.close()
probes.clear()
restarted = restart_api(client, containers) if args.restart_api else None
for container in containers:
probe = metrics.MemoryProbe(container)
probes.append(probe)
probe.ready = probe.receive('ready')
def upload():
if mode == 'direct':
cap = grant(client, owner, chat, image)
put(client, cap, image)
response = complete(client, owner, cap)
else:
response = client.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=benchmark.png", 201,
actor=owner, raw=image, headers={'Content-Type': 'image/png'}, schema='Attachment')
return response['json'], response['headers']['X-Instance-Id'], response['headers']['X-Request-Id']
# Warm the selected workflow before recording it. Warm-up failures fail the run.
warmed = set()
for warmup_index in range(warmups):
# Vary request parity so least_conn does not pin every complete
# to the same replica in the four-request direct workflow.
if args.restart_api and warmup_index % 2:
client.call('GET', '/health/live')
attachment, instance, _ = upload()
warmed.add(instance)
verify(client, reader, attachment, image)
if args.restart_api:
check(warmed == {probe.ready['instance'] for probe in probes}, 'Warm-up did not cover both API replicas')
for probe in probes: probe.command('begin', 'begin')
started = time.monotonic()
attachments = []
request_ids = []
try:
for _ in range(args.repeats):
attachment, _, request_id = upload()
attachments.append(attachment)
request_ids.append(request_id)
finally:
elapsed = time.monotonic() - started
samples = [{'instance': probe.ready['instance'], **probe.command('end', 'summary')} for probe in probes]
report['cases'].append({'round': round_number, 'mode': mode, 'sidePixels': side, 'fileBytes': len(image),
'apiStatesAfterRestart': restarted, 'warmupInstances': sorted(warmed),
'requestIds': request_ids,
'successfulUploads': len(attachments), 'elapsedSeconds': elapsed,
'memory': samples, 'apiRxBytes': sum(m['networkRxBytes'] for m in samples),
'apiTxBytes': sum(m['networkTxBytes'] for m in samples)})
for sample in samples:
check(sample['samples'] >= 2 and sample['oomDelta'] == sample['oomKillDelta'] == 0, 'Invalid memory samples or OOM')
if args.profile:
time.sleep(5)
report['cases'][-1]['idleAfterFiveSeconds'] = [
{'instance': probe.ready['instance'], **probe.command('snapshot', 'snapshot')} for probe in probes]
collect_profiles(report['cases'][-1], log_start, args.repeats)
for attachment in attachments: verify(client, reader, attachment, image)
print(f"PASS: round {round_number}, {mode}, {side}px, {len(image)} bytes, {len(attachments)} uploads; API RX/TX={sum(m['networkRxBytes'] for m in samples)}/{sum(m['networkTxBytes'] for m in samples)}", flush=True)
for probe in probes: probe.close()
probes.clear()
report['fixturesRemoved'] = True
report['status'] = 'passed'
except BaseException as error:
report['errorType'] = type(error).__name__
if isinstance(error, Failure): report['failure'] = str(error)
raise
finally:
for probe in probes: probe.close()
filename = 'direct-upload-memory-profile.json' if args.profile else (
'direct-upload-benchmark-restarted.json' if args.restart_api else 'direct-upload-benchmark.json')
(ROOT / 'evidence' / filename).write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+237
View File
@@ -0,0 +1,237 @@
"""Compare proxy/direct uploads under synchronized load; measure the main API processes."""
import argparse
import base64
from concurrent.futures import ThreadPoolExecutor
import hashlib
import http.client
import importlib.util
import json
import statistics
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
from direct_client import ROOT, Client, Failure, check, docker, fixture, grant, put, complete, verify
spec = importlib.util.spec_from_file_location('direct_benchmark', ROOT / 'test/direct-upload-benchmark.py')
benchmark = importlib.util.module_from_spec(spec)
spec.loader.exec_module(benchmark)
metrics = benchmark.metrics
class HttpFailure(Failure):
def __init__(self, stage, status, headers):
super().__init__(f'{stage} returned HTTP {status}')
self.details = {'stage': stage, 'status': status,
'instance': headers.get('X-Instance-Id'), 'requestId': headers.get('X-Request-Id')}
def paced_request(method, url, headers, image, gate, duration):
target = urlsplit(url)
check(target.scheme == 'http', 'This benchmark targets the local HTTP stack')
connection = http.client.HTTPConnection(target.hostname, target.port, timeout=60)
try:
connection.putrequest(method, target.path + ('?' + target.query if target.query else ''))
for name, value in headers.items(): connection.putheader(name, value)
connection.endheaders()
first = min(65536, len(image) - 1)
connection.send(image[:first])
gate.wait(timeout=60)
started = time.monotonic()
for offset in range(first, len(image), 65536):
end = min(offset + 65536, len(image))
deadline = started + duration * (end - first) / (len(image) - first)
time.sleep(max(0, deadline - time.monotonic()))
connection.send(image[offset:end])
response = connection.getresponse()
body = response.read(1024 * 1024 + 1)
check(len(body) <= 1024 * 1024, 'Unexpectedly large response')
return response.status, response.headers, body
finally:
connection.close()
def error_result(error, stage):
# Never serialize exceptions containing a signed URL or request headers.
return {'ok': False, 'stage': stage, 'errorType': type(error).__name__,
**getattr(error, 'details', {})}
def upload(client, owner, chat, image, digest, mode, gate, completion_gate, duration):
started = time.monotonic()
error = None
attachment = None
instance = None
stage = 'grant' if mode == 'direct' else 'proxy'
try:
if mode == 'direct':
capability = grant(client, owner, chat, image)
stage = 'put'
status, headers, _ = paced_request('PUT', capability['url'], capability['headers'], image, gate, duration)
if status != 200: raise HttpFailure(stage, status, headers)
else:
status, headers, body = paced_request(
'POST', client.base + f"/api/v1/chats/{chat['id']}/attachments?filename=load.png",
{'Authorization': 'Bearer ' + owner['token'], 'Content-Type': 'image/png',
'Content-Length': str(len(image))}, image, gate, duration)
if status != 201: raise HttpFailure(stage, status, headers)
attachment = metrics.shape(json.loads(body), 'Attachment')
instance = headers.get('X-Instance-Id')
except Exception as caught:
error = error_result(caught, stage)
gate.abort()
if mode == 'direct':
# All workers arrive even if their PUT failed; successful PUTs can still complete.
try:
completion_gate.wait(timeout=65)
if error is None:
stage = 'complete'
response = complete(client, owner, capability, [201, 400, 401, 404, 408, 409, 413, 415, 429, 500, 503])
if response['status'] != 201: raise HttpFailure(stage, response['status'], response['headers'])
attachment = metrics.shape(json.loads(response['bytes']), 'Attachment')
instance = response['headers'].get('X-Instance-Id')
except Exception as caught:
if error is None: error = error_result(caught, stage)
if error is None:
try:
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(image), 'Incorrect checksum/size')
check(attachment['chat_id'] == chat['id'] and attachment['owner_id'] == owner['id'], 'Incorrect ownership')
check(bool(instance), 'Missing instance ID')
except Exception as caught:
error = error_result(caught, 'validate_response')
return {**(error or {'ok': True, 'attachment': attachment, 'instance': instance}),
'elapsedSeconds': time.monotonic() - started}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--sizes', type=int, nargs='+', default=[1792])
parser.add_argument('--concurrency', type=int, nargs='+', default=[1, 5, 10])
parser.add_argument('--rounds', type=int, default=2)
parser.add_argument('--waves', type=int, default=2)
parser.add_argument('--upload-seconds', type=float, default=2)
args = parser.parse_args()
check(all(64 <= n <= 1800 for n in args.sizes), 'Invalid image size')
check(all(1 <= n <= 20 for n in args.concurrency), 'Concurrency must be 1..20')
check(1 <= args.rounds <= 3 and 1 <= args.waves <= 5, 'Invalid rounds/waves')
check(0.1 <= args.upload_seconds <= 5, 'Pacing must be 0.1..5 seconds')
report = {'status': 'running', 'cases': [], 'settings': vars(args),
'method': 'Fresh API restart per case, exactly 2 verified warm-up uploads per replica via internal API addresses; temporary docker-exec client exits before measurement. Measured uploads use public Nginx. Two paced waves by default; all bodies are incomplete at the upload barrier, direct completes start at a second barrier. Full workflow latency includes grant/PUT/complete. External per-API-process RSS sampling at 50 ms; cgroup memory recorded separately. Independent replica peaks are not summed. No retries. Download verification is outside the measurement window.'}
output = ROOT / 'evidence/direct-upload-load.json'
def save(): output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
probes = []
try:
readiness = Client('http://127.0.0.1:8080', timeout=5)
deadline = time.monotonic() + 90
routed = set()
while time.monotonic() < deadline:
try: routed.add(readiness.call('GET', '/health/ready')['headers']['X-Instance-Id'])
except Failure: pass
if len(routed) == 2: break
time.sleep(1)
check(len(routed) == 2, 'Both API replicas must be ready')
with fixture() as (client, owner, reader, chat, _):
containers = docker('compose', 'ps', '-q', 'api').split()
check(len(containers) == 2, 'Expected two replicas')
for container in containers:
flag = docker('exec', container, 'node', '-p', "process.env.UPLOAD_MEMORY_PROFILE || '0'").strip()
check(flag == '0', 'Disable detailed profiling for the load comparison')
cases = [(r + 1, side, concurrency, mode) for r in range(args.rounds)
for side in args.sizes for concurrency in args.concurrency
for mode in (['proxy', 'direct'] if r % 2 == 0 else ['direct', 'proxy'])]
for round_number, side, concurrency, mode in cases:
image = metrics.png_image(side) + metrics.chunk(b'IEND', b'')
digest = hashlib.sha256(image).hexdigest()
for probe in probes: probe.close()
probes.clear()
restarted = benchmark.restart_api(client, containers)
for container in containers:
probe = metrics.MemoryProbe(container)
probes.append(probe)
probe.ready = probe.receive('ready')
target_rows = docker('inspect', '--format', '{{.Config.Hostname}} {{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}', *containers).splitlines()
targets = [{'instance': row.split()[0], 'address': row.split()[1]} for row in target_rows]
source = (ROOT / 'test/warm-upload-replicas.mjs').read_text(encoding='utf-8')
warmup = json.loads(docker('exec', '-i', containers[0], 'node', '--input-type=module', '-e', source,
input=json.dumps({'targets': targets, 'owner': owner, 'reader': reader,
'chat': chat, 'imageBase64': base64.b64encode(image).decode(), 'mode': mode})))
check(warmup['counts'] == {p.ready['instance']: 2 for p in probes}, 'Unequal per-replica warm-up')
identities = docker('inspect', '--format', '{{.State.StartedAt}} {{.RestartCount}} {{.State.OOMKilled}} {{.State.Running}}', *containers)
workers = [Client(client.base, timeout=60) for _ in range(concurrency)]
case = {'round': round_number, 'sidePixels': side, 'fileBytes': len(image), 'mode': mode,
'concurrency': concurrency, 'apiStatesAfterRestart': restarted,
'warmupCounts': warmup['counts'], 'waves': [], 'verifiedDownloads': 0}
report['cases'].append(case)
results = []
for probe in probes: probe.command('begin', 'begin')
started = time.monotonic()
try:
with ThreadPoolExecutor(max_workers=concurrency) as pool:
for wave in range(args.waves):
gate = threading.Barrier(concurrency + 1)
complete_gate = threading.Barrier(concurrency)
futures = [pool.submit(upload, worker, owner, chat, image, digest, mode, gate, complete_gate, args.upload_seconds)
for worker in workers]
overlapped = False
try:
gate.wait(timeout=60)
overlapped = True
except threading.BrokenBarrierError: pass
wave_results = [future.result() for future in futures]
results.extend(wave_results)
case['waves'].append({'wave': wave + 1,
'incompleteBodiesAtBarrier': concurrency if overlapped else 0,
'attempts': [{k: v for k, v in result.items() if k != 'attachment'} for result in wave_results]})
finally:
case['elapsedSeconds'] = time.monotonic() - started
case['memory'] = [{'instance': p.ready['instance'], **p.command('end', 'summary')} for p in probes]
case['successfulUploads'] = sum(result['ok'] for result in results)
case['failedUploads'] = len(results) - case['successfulUploads']
case['successfulUploadsPerSecond'] = case['successfulUploads'] / case['elapsedSeconds']
case['instances'] = {name: sum(r['ok'] and r.get('instance') == name for r in results)
for name in sorted({r['instance'] for r in results if r['ok']})}
latencies = sorted(result['elapsedSeconds'] for result in results)
case['latencySeconds'] = {'median': statistics.median(latencies), 'max': max(latencies)}
case['apiIdentityUnchanged'] = identities == docker('inspect', '--format', '{{.State.StartedAt}} {{.RestartCount}} {{.State.OOMKilled}} {{.State.Running}}', *containers)
save()
check(case['apiIdentityUnchanged'], 'API restarted during load')
for sample in case['memory']:
check(sample['samples'] >= 2, 'Insufficient RSS samples')
check(sample['oomDelta'] == sample['oomKillDelta'] == 0, 'API OOM; stopping further load')
for result in results:
if result['ok']:
verify(client, reader, result['attachment'], image)
case['verifiedDownloads'] += 1
check(len({r['attachment']['id'] for r in results if r['ok']}) == case['successfulUploads'], 'Duplicate attachment IDs')
if concurrency >= 5 and case['failedUploads'] == 0:
check(len(case['instances']) == 2, 'Concurrent work did not reach both replicas')
try:
case['apiReadyAfterCase'] = client.call('GET', '/health/ready')['status'] == 200
except Failure:
case['apiReadyAfterCase'] = False
save()
peaks = ', '.join(f"{m['sampledPeakRssBytes'] / 2**20:.1f}" for m in case['memory'])
print(f"DONE: round {round_number}, {mode}, {side}px, N={concurrency}, {case['successfulUploads']}/{len(results)}, RSS MiB=[{peaks}]", flush=True)
for probe in probes: probe.close()
probes.clear()
report['fixturesRemoved'] = True
report['status'] = 'completed_with_errors' if any(c['failedUploads'] or not c['apiReadyAfterCase'] for c in report['cases']) else 'passed'
return report['status'] == 'passed'
except BaseException as error:
report['status'] = 'failed'
report['errorType'] = type(error).__name__
if isinstance(error, Failure): report['failure'] = str(error)
raise
finally:
for probe in probes: probe.close()
save()
if __name__ == '__main__':
try:
sys.exit(0 if main() else 1)
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+134
View File
@@ -0,0 +1,134 @@
"""Positive and negative presigned-upload scenarios on the pinned Compose stack."""
import hashlib
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import struct
import subprocess
import sys
import time
from threading import Barrier
from urllib.parse import urlsplit, urlunsplit
import zlib
from direct_client import ROOT, Failure, check, fixture, grant, put, complete, verify, cleanup_staging
def main():
report = {'status': 'failed', 'checks': []}
def passed(name):
report['checks'].append(name)
print('PASS: ' + name, flush=True)
try:
with fixture() as (client, owner, reader, chat, foreign_chat):
image = (ROOT / 'tests/fixtures/sample.png').read_bytes()
cap = grant(client, owner, chat, image)
path = f"/api/v1/chats/{chat['id']}/attachment-uploads"
fields = {'filename': 'direct.png', 'content_type': 'image/png', 'size_bytes': len(image),
'sha256': hashlib.sha256(image).hexdigest()}
client.call('POST', path, 401, body=fields)
client.call('POST', f"/api/v1/chats/{foreign_chat['id']}/attachment-uploads", 404, actor=owner, body=fields)
client.call('POST', path, 413, actor=owner, body={**fields, 'size_bytes': 10485761})
client.call('POST', path, 400, actor=owner, body={**fields, 'filename': '../escape.png'})
client.call('POST', path, 400, actor=owner, body={**fields, 'expires_in': 301})
complete(client, reader, cap, 404)
complete(client, owner, cap, 404, path=cap['complete_url'].replace(chat['id'], foreign_chat['id']))
complete(client, owner, cap, 409)
passed('grant ACL, strict input validation, owner-only complete and missing-upload handling')
parsed = urlsplit(cap['url'])
unsigned = urlunsplit((parsed.scheme, parsed.netloc, parsed.path, '', ''))
put(client, cap, image, 403, url=unsigned)
put(client, cap, image, 403, headers={**cap['headers'], 'Content-Type': 'image/jpeg'})
put(client, cap, image + b'x', 403, headers={**cap['headers'], 'Content-Length': str(len(image) + 1)})
put(client, cap, image, 403, headers={**cap['headers'], 'If-None-Match': 'not-the-signed-value'})
altered = bytes([image[0] ^ 1]) + image[1:]
put(client, cap, altered, 400)
passed('unsigned/tampered requests denied; wrong payload checksum rejected by RustFS')
put(client, cap, image)
put(client, cap, image, 412)
attachment = complete(client, owner, cap)['json']
check(attachment['id'] == cap['upload_id'], 'Unexpected attachment ID')
verify(client, reader, attachment, image)
check(complete(client, owner, cap)['json'] == attachment, 'Complete replay changed its result')
# URLs may be reused until expiry, but only in staging; the original must stay immutable.
put(client, cap, image)
check(complete(client, owner, cap)['json'] == attachment, 'Late PUT changed publication')
verify(client, reader, attachment, image)
client.message(owner, chat, '', attachments=[attachment['id']])
passed('create-only PUT, publication, byte integrity, message binding and replay-safe immutable original')
jpeg = subprocess.run(['node', '-e', "require('sharp')('tests/fixtures/sample.png').jpeg().toBuffer().then(b=>process.stdout.write(b))"],
cwd=ROOT, capture_output=True, check=True).stdout
jpg_cap = grant(client, owner, chat, jpeg, filename='direct.jpg', content_type='image/jpeg')
put(client, jpg_cap, jpeg)
verify(client, reader, complete(client, owner, jpg_cap)['json'], jpeg)
passed('JPEG publication preserves the exact original bytes')
racing = grant(client, owner, chat, image)
put(client, racing, image)
barrier = Barrier(4)
def finish(_):
barrier.wait(timeout=30)
return complete(client, owner, racing, [201, 409])
with ThreadPoolExecutor(max_workers=4) as pool:
replies = list(pool.map(finish, range(4)))
published = complete(client, owner, racing)['json']
check(any(reply['status'] == 201 for reply in replies), 'No concurrent complete succeeded')
for reply in replies:
if reply['status'] == 201:
check(json.loads(reply['bytes']) == published, 'Concurrent publication returned different metadata')
verify(client, reader, published, image)
passed('simultaneous complete publishes one stable attachment across replicas')
for payload, mime, expected in [(b'not an image', 'image/png', 415), (image, 'image/jpeg', 415)]:
invalid = grant(client, owner, chat, payload, content_type=mime)
put(client, invalid, payload)
complete(client, owner, invalid, expected)
complete(client, owner, invalid, 409)
client.call('GET', '/api/v1/attachments/' + invalid['upload_id'], 404, actor=owner)
passed('corrupt image and MIME spoof rejected without ready metadata')
def chunk(kind, value):
return struct.pack('>I', len(value)) + kind + value + struct.pack('>I', zlib.crc32(kind + value))
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0))
huge += chunk(b'IDAT', zlib.compress(b'\x00\x00\x00\x00')) + chunk(b'IEND', b'')
invalid = grant(client, owner, chat, huge)
put(client, invalid, huge)
complete(client, owner, invalid, 413)
passed('40-million-pixel limit enforced before full decoding')
expired = grant(client, owner, chat, image, expires_in=3)
put(client, expired, image)
expired_empty = grant(client, owner, chat, image, expires_in=3)
time.sleep(4.2)
# Test expiry on a missing key: an existing object may yield 412 first.
put(client, expired_empty, image, 403)
put(client, expired, image, [403, 412])
complete(client, owner, expired, 409)
swept = cleanup_staging(chat['id'])
check(swept['stagingDeleted'] >= 1, 'Expired staging object was not cleaned')
verify(client, reader, attachment, image)
passed('real URL expiry, expired-intent cleanup and published-object protection')
proxy = client.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=proxy.png", 201,
actor=owner, raw=image, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
verify(client, reader, proxy, image)
passed('mandatory proxy upload remains compatible')
report['status'] = 'passed'
report['fixturesRemoved'] = True
except BaseException as error:
report['errorType'] = type(error).__name__
if isinstance(error, Failure): report['failure'] = str(error)
raise
finally:
(ROOT / 'evidence/direct-uploads.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+95
View File
@@ -0,0 +1,95 @@
"""Shared direct-upload fixtures. Signed URLs and credentials are never logged or persisted."""
import base64
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check
def docker(*args, **kwargs):
return subprocess.run(['docker', *args], cwd=ROOT, capture_output=True,
text=True, timeout=120, check=True, **kwargs).stdout
def grant(client, owner, chat, payload, **overrides):
fields = {'filename': 'direct.png', 'content_type': 'image/png',
'size_bytes': len(payload), 'sha256': hashlib.sha256(payload).hexdigest(), **overrides}
response = client.call('POST', f"/api/v1/chats/{chat['id']}/attachment-uploads", 201, actor=owner, body=fields)
check(response['headers'].get('Cache-Control') == 'no-store', 'Capability response must not be cached')
value = json.loads(response['bytes'])
check(value['method'] == 'PUT' and value['headers']['If-None-Match'] == '*', 'Incorrect upload constraints')
return value
def put(client, capability, payload, expected=200, headers=None, url=None):
request = urllib.request.Request(url or capability['url'], data=payload, method='PUT',
headers=headers if headers is not None else capability['headers'])
try:
response = client.opener.open(request, timeout=60)
except urllib.error.HTTPError as error:
response = error
except (OSError, urllib.error.URLError) as error:
raise Failure('Signed PUT connection failure: ' + type(error).__name__) from None
with response:
status = response.code
response.read(1024 * 1024)
allowed = [expected] if isinstance(expected, int) else expected
check(status in allowed, f'Signed PUT returned {status}; expected {allowed}')
return status
def complete(client, owner, capability, expected=201, path=None):
return client.call('POST', path or capability['complete_url'], expected, actor=owner, body={},
schema='Attachment' if expected == 201 else None)
def verify(client, reader, attachment, payload):
path = '/api/v1/attachments/' + attachment['id']
check(client.call('GET', path, actor=reader, schema='Attachment')['json'] == attachment, 'Metadata changed')
downloaded = client.call('GET', path + '/content', actor=reader)['bytes']
check(downloaded == payload, 'Published original bytes differ')
check(attachment['sha256'] == hashlib.sha256(payload).hexdigest(), 'Published checksum differs')
@contextmanager
def fixture():
client = Client('http://127.0.0.1:8080', timeout=60)
run_id = str(uuid.uuid4())
actors, chats = [], []
try:
for suffix in ['a', 'b']:
actors.append(client.user('cu' + run_id[:8] + suffix))
for members, actor in [([a['id'] for a in actors], actors[0]), ([actors[1]['id']], actors[1])]:
chats.append(client.call('POST', '/api/v1/chats', 201, actor=actor, schema='Chat',
body={'title': 'direct-upload:' + run_id, 'member_ids': members})['json'])
yield client, actors[0], actors[1], chats[0], chats[1]
finally:
source = (ROOT / 'test/concurrent-cleanup.mjs').read_text(encoding='utf-8')
payload = json.dumps({'runId': run_id, 'chatIds': [chat['id'] for chat in chats],
'userIds': [actor['id'] for actor in actors], 'kind': 'direct-upload'})
docker('compose', 'exec', '-T', '--index', '1', 'api', 'node', '--input-type=module', '-e', source, input=payload)
def cleanup_staging(chat_id):
source = """const {createRequire}=await import('node:module');
const require=createRequire(process.cwd()+'/package.json');
const {PrismaService}=require('./dist/prisma/prisma.service.js');
const {StorageService}=require('./dist/Storage/storage.service.js');
const {cleanStaging}=require('./dist/Attachment/staging-cleanup.js');
let input='';for await(const chunk of process.stdin)input+=chunk;
const chat=JSON.parse(input).chat;
if(!/^[0-9a-f-]{36}$/.test(chat))throw Error('invalid fixture chat');
const db=new PrismaService();const storage=new StorageService();
try{await db.onModuleInit();const report=await cleanStaging(db,storage,{apply:true,graceSeconds:1,prefix:'originals/'+chat+'/'},new Date());console.log(JSON.stringify(report));}
finally{storage.onModuleDestroy();await db.onModuleDestroy();}"""
return json.loads(docker('compose', 'exec', '-T', 'reconciler', 'node', '--input-type=module', '-e', source,
input=json.dumps({'chat': chat_id})).strip())
+162
View File
@@ -0,0 +1,162 @@
"""Run the existing regression suites sequentially and restore the local Compose stack."""
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
from queue import Queue, Empty
import subprocess
import sys
import threading
import time
from direct_client import ROOT, Client, Failure, check, docker
RUNTIME = {'api', 'nginx', 'postgres', 'redis', 's3', 'reconciler'}
def fingerprint():
paths = {ROOT / name for name in ['Dockerfile', 'compose.yaml', 'package.json', 'pnpm-lock.yaml',
'tsconfig.json', 'tsconfig.build.json', 'nest-cli.json', 'prisma.config.ts']}
for directory in ['src', 'prisma', 'test', 'tests', 'scripts', 'contracts', 'infra']:
paths.update(path for path in (ROOT / directory).rglob('*') if path.is_file()
and 'generated' not in path.parts and '__pycache__' not in path.parts)
digest = hashlib.sha256()
for path in sorted(paths):
digest.update(path.relative_to(ROOT).as_posix().encode() + b'\0' + path.read_bytes() + b'\0')
return digest.hexdigest()
def states():
raw = docker('compose', 'ps', '--all', '--format', 'json').strip()
records = json.loads(raw) if raw.startswith('[') else [json.loads(line) for line in raw.splitlines()]
return [{'service': r['Service'], 'name': r['Name'], 'id': r['ID'],
'state': r['State'], 'health': r.get('Health', ''), 'image': r['Image']}
for r in records if r['Service'] in RUNTIME]
def healthy(records):
return (len(records) == 7 and sum(r['service'] == 'api' for r in records) == 2
and {r['service'] for r in records} == RUNTIME
and all(r['state'] == 'running' and r['health'] == 'healthy' for r in records))
def wait_ready():
client = Client('http://127.0.0.1:8080', timeout=5)
routed = set()
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
current = states()
if healthy(current):
try:
routed.add(client.call('GET', '/health/ready')['headers']['X-Instance-Id'])
if len(routed) == 2: return current
except Failure: pass
time.sleep(1)
raise Failure('Complete stack and both Nginx upstreams did not become ready')
def main():
report = {'status': 'running', 'startedAt': datetime.now(timezone.utc).isoformat(),
'sourceSha256': fingerprint(), 'steps': [],
'scope': 'Existing suites, sequential execution, no load benchmark rerun. IPv4 public endpoint. All runtime services restored without deleting volumes.'}
output = ROOT / 'evidence/final-regression.json'
def save(): output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
def step(name, command, timeout):
entry = {'name': name, 'command': command, 'status': 'running', 'output': []}
report['steps'].append(entry)
save()
print('START: ' + name, flush=True)
started = time.monotonic()
process = subprocess.Popen(command, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', errors='replace', bufsize=1)
messages = Queue()
def read():
try:
for line in process.stdout: messages.put(line.rstrip())
finally: messages.put(None)
threading.Thread(target=read, daemon=True).start()
try:
while True:
if time.monotonic() - started > timeout:
process.kill()
process.wait(timeout=15)
raise Failure('Regression step timed out: ' + name)
try: line = messages.get(timeout=1)
except Empty: continue
if line is None: break
# Keep deliberately emitted test results only; no request/env dumps or stacks.
if line.startswith(('PASS:', 'FAIL:', 'Test Suites:', 'Tests:')):
entry['output'].append(line)
print(line, flush=True)
entry['exitCode'] = process.wait(timeout=15)
check(entry['exitCode'] == 0, f'Regression step failed: {name} (exit {entry["exitCode"]})')
entry['status'] = 'passed'
print('PASS: regression step ' + name, flush=True)
except BaseException:
entry['status'] = 'failed'
if process.poll() is None:
process.kill()
process.wait(timeout=15)
raise
finally:
process.stdout.close()
entry['elapsedSeconds'] = time.monotonic() - started
save()
py = [sys.executable, '-X', 'utf8', '-u']
pnpm = ['cmd.exe', '/d', '/c', 'pnpm.cmd'] if os.name == 'nt' else ['pnpm']
try:
report['before'] = wait_ready()
api_ids = docker('compose', 'ps', '-q', 'api').split()
report['apiImages'] = docker('inspect', '--format', '{{.Config.Hostname}} {{.Image}}', *api_ids).splitlines()
for container in api_ids:
check(docker('exec', container, 'node', '-p', "process.env.UPLOAD_MEMORY_PROFILE || '0'").strip() == '0', 'Disable diagnostic profiling')
step('offline_contract', py + ['scripts/check_contract.py'], 90)
step('unit', pnpm + ['test', '--runInBand'], 240)
step('lint', pnpm + ['lint'], 180)
step('public_smoke_before', py + ['tests/smoke.py', '--base-url', 'http://127.0.0.1:8080'], 120)
step('oversized_upload_transport', py + ['test/oversized-uploads.py'], 180)
step('attachments_s3_outage_persistence', py + ['test/attachments.py', '--base-url', 'http://127.0.0.1:8080', '--lifecycle'], 600)
wait_ready()
step('reconciliation_crash_and_database_outage', py + ['test/run-reconcile.py'], 180)
step('public_persistence_and_each_api_failover', py + ['test/hooks.py'], 1200)
wait_ready()
step('swagger_and_attachment_failover', py + ['test/replicas.py', '--base-url', 'http://127.0.0.1:8080'], 240)
wait_ready()
step('interrupted_upload_and_receive_deadline', py + ['test/upload-interruption.py'], 240)
step('presigned_positive_and_negative', py + ['test/direct-uploads.py'], 240)
for name, script in [('s3_restricted_roles', 's3-permissions.mjs'),
('s3_conditional_write_checksum_copy', 's3-direct-capabilities.mjs')]:
step(name, ['docker', 'compose', 'run', '--rm', '--no-deps', '-T',
'-v', f'{ROOT / "test"}:/app/test:ro', '--entrypoint', 'node', 's3-init', 'test/' + script], 180)
step('public_smoke_after', py + ['tests/smoke.py', '--base-url', 'http://127.0.0.1:8080'], 120)
report['sourceUnchanged'] = fingerprint() == report['sourceSha256']
check(report['sourceUnchanged'], 'Source changed during regression')
report['status'] = 'passed'
except BaseException as error:
report['status'] = 'failed'
report['errorType'] = type(error).__name__
if isinstance(error, Failure): report['failure'] = str(error)
raise
finally:
try:
if not healthy(states()):
docker('compose', 'up', '-d', '--no-build', '--wait', '--wait-timeout', '180')
report['after'] = wait_ready()
report['stackRestored'] = True
except Exception as error:
report['stackRestored'] = False
report['restoreErrorType'] = type(error).__name__
report['status'] = 'failed'
report['finishedAt'] = datetime.now(timezone.utc).isoformat()
save()
check(report['status'] == 'passed' and report['stackRestored'], 'Final regression or stack restoration failed')
print('PASS: final regression; all suites passed; complete stack ready', flush=True)
if __name__ == '__main__':
try:
main()
except (Failure, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+133
View File
@@ -0,0 +1,133 @@
"""Run unchanged public resilience tests and record which Compose processes changed."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
def docker(*args):
return subprocess.run(['docker', *args], cwd=ROOT, capture_output=True,
text=True, check=True, timeout=120).stdout
def snapshot():
ids = docker('compose', 'ps', '--all', '-q').split()
states = json.loads(docker('inspect', *ids))
return {state['Name'].lstrip('/'): {
'service': state['Config']['Labels']['com.docker.compose.service'],
'instance': state['Config']['Hostname'], 'startedAt': state['State']['StartedAt'],
'status': state['State']['Status'], 'restartCount': state['RestartCount'],
} for state in states if state['Config']['Labels']['com.docker.compose.service']
in {'api', 'nginx', 'postgres', 'redis', 's3', 'reconciler'}}
def public_test(mode):
extension = 'cmd' if os.name == 'nt' else 'sh'
hook = ROOT / 'scripts' / (('restart.' if mode == 'persistence' else 'stop-one.') + extension)
result = subprocess.run([sys.executable, '-X', 'utf8', '-u', str(ROOT / 'tests/resilience.py'),
'--mode', mode, '--action-script', str(hook), '--base-url', 'http://127.0.0.1:8080'],
cwd=ROOT, capture_output=True, text=True, timeout=240)
print(result.stdout, end='', flush=True)
if result.returncode:
raise RuntimeError(f'Public {mode} test failed: {result.stderr.strip() or result.stdout.strip()}')
return result.stdout.strip()
def warm_writes():
# Exercise writes and attachment I/O before measuring a steady-state API failure.
client = Client('http://127.0.0.1:8080', timeout=10)
alice, _, _, chat = client.bootstrap()
timings = {}
for index in range(30):
result = client.message(alice, chat, f'Failover warm-up {index}')
timings.setdefault(result['headers']['X-Instance-Id'], []).append(result['elapsed'])
if len(timings) == 2 and min(map(len, timings.values())) >= 3:
break
assert len(timings) == 2 and min(map(len, timings.values())) >= 3, 'Warm-up did not reach both API write paths'
result = {instance: {'writes': len(values), 'minSeconds': min(values), 'maxSeconds': max(values),
'uploadSeconds': [], 'downloadSeconds': []}
for instance, values in timings.items()}
image = (ROOT / 'tests/fixtures/sample.png').read_bytes()
for index in range(30):
uploaded = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=warmup.png',
201, actor=alice, raw=image, headers={'Content-Type': 'image/png'}, schema='Attachment')
result[uploaded['headers']['X-Instance-Id']]['uploadSeconds'].append(uploaded['elapsed'])
path = '/api/v1/attachments/' + uploaded['json']['id']
client.call('GET', path, actor=alice, schema='Attachment')
downloaded = client.call('GET', path + '/content', actor=alice)
assert downloaded['bytes'] == image, 'Warm-up attachment checksum mismatch'
result[downloaded['headers']['X-Instance-Id']]['downloadSeconds'].append(downloaded['elapsed'])
if all(entry['uploadSeconds'] and entry['downloadSeconds'] for entry in result.values()):
break
assert all(entry['uploadSeconds'] and entry['downloadSeconds'] for entry in result.values()), 'Attachment warm-up did not reach both replicas'
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--mode', choices=['all', 'failover'], default='all')
args = parser.parse_args()
report = {'status': 'failed', 'failover': []}
report['writeWarmups'] = []
try:
before = snapshot()
assert sum(state['service'] == 'api' for state in before.values()) == 2, 'Expected two API replicas'
assert all(state['status'] == 'running' for state in before.values()), 'Start the complete stack first'
if args.mode == 'all':
output = public_test('persistence')
after = snapshot()
assert before.keys() == after.keys(), 'Restart hook recreated runtime containers'
assert all(state['startedAt'] != before[name]['startedAt'] and state['status'] == 'running'
for name, state in after.items()), 'Hook did not restart every runtime service'
report['persistence'] = {'before': before, 'after': after, 'output': output}
else:
previous = json.loads((ROOT / 'evidence/hooks.json').read_text(encoding='utf-8'))
assert previous.get('persistence'), 'Run the full suite first to record persistence evidence'
report['persistence'] = previous['persistence']
report['persistenceEvidenceReused'] = True
after = before
expected = {state['instance'] for state in after.values() if state['service'] == 'api'}
stopped_instances = set()
# The public test selects the replica that served its POST, so repeat independent
# successful scenarios until each replica has been targeted. No failing run is retried.
for _ in range(6):
if stopped_instances == expected:
break
before = snapshot()
try:
report['writeWarmups'].append(warm_writes())
output = public_test('failover')
after = snapshot()
stopped = [state for state in after.values() if state['service'] == 'api' and state['status'] == 'exited']
assert len(stopped) == 1, 'Stop-one hook did not leave exactly one API stopped'
assert all(state['startedAt'] == before[name]['startedAt'] and state['status'] == 'running'
for name, state in after.items() if state['service'] != 'api'), 'Failover touched non-API services'
target = stopped[0]['instance']
stopped_instances.add(target)
report['failover'].append({'stoppedInstance': target, 'before': before, 'after': after, 'output': output})
finally:
docker('compose', 'up', '-d', '--no-deps', '--no-recreate', '--no-build', '--wait', '--wait-timeout', '90', 'api')
time.sleep(5) # Allow the Nginx readiness poll to observe the restored API.
assert stopped_instances == expected, 'Public scenarios did not cover both API replicas'
report['status'] = 'passed'
print('PASS: public persistence/failover hooks; all stores restarted; each API stopped separately; replicas restored')
except (AssertionError, RuntimeError, OSError, subprocess.SubprocessError) as error:
report['error'] = str(error) if isinstance(error, (AssertionError, RuntimeError)) else type(error).__name__
raise
finally:
(ROOT / 'evidence/hooks.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
main()
except (AssertionError, RuntimeError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, (AssertionError, RuntimeError)) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+45
View File
@@ -0,0 +1,45 @@
"""Real Nginx/API rejection of oversized Content-Length and chunked bodies."""
import json
import subprocess
import sys
from direct_client import ROOT, Failure, check, fixture, verify
def main():
report = {'status': 'failed', 'attempts': []}
try:
with fixture() as (client, owner, reader, chat, _):
payload = b'x' * (10485760 + 1)
path = f"/api/v1/chats/{chat['id']}/attachments?filename=oversize.png"
for index in range(16):
mode = 'content-length' if index % 2 == 0 else 'chunked'
body = payload if mode == 'content-length' else (
payload[offset:offset + 65536] for offset in range(0, len(payload), 65536))
result = client.call('POST', path, 413, actor=owner, raw=body,
headers={'Content-Type': 'image/png'})
check(result['json']['error']['code'] == 'payload_too_large', 'Incorrect error code')
report['attempts'].append({'mode': mode, 'status': result['status'],
'instance': result['headers']['X-Instance-Id']})
check(len({row['instance'] for row in report['attempts']}) == 2, 'Oversize requests missed a replica')
image = (ROOT / 'tests/fixtures/sample.png').read_bytes()
attachment = client.call('POST', path.replace('oversize.png', 'valid.png'), 201,
actor=owner, raw=image, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
verify(client, reader, attachment, image)
report['fixturesRemoved'] = True
report['status'] = 'passed'
print('PASS: 16 oversized Content-Length/chunked uploads through Nginx returned canonical 413; both APIs covered; subsequent upload/download verified')
except BaseException as error:
report['errorType'] = type(error).__name__
if isinstance(error, Failure): report['failure'] = str(error)
raise
finally:
(ROOT / 'evidence/oversized-uploads.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+224
View File
@@ -0,0 +1,224 @@
// Run through test/run-reconcile.py with distinct writer/scanner credentials.
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { randomUUID, createHash } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
const require = createRequire(`${process.cwd()}/package.json`);
const { PrismaService } = require('./dist/prisma/prisma.service.js');
const { StorageService } = require('./dist/Storage/storage.service.js');
const { ReconcileService } = require('./dist/Attachment/reconcile.service.js');
const db = new PrismaService();
const storage = new StorageService();
const scannerCredentials = JSON.parse(
process.env.RECONCILE_TEST_SCANNER_CREDENTIALS,
);
delete process.env.RECONCILE_TEST_SCANNER_CREDENTIALS;
const writerCredentials = {
S3_ACCESS_KEY_ID: process.env.S3_ACCESS_KEY_ID,
S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY,
};
Object.assign(process.env, scannerCredentials);
const scanner = new StorageService();
Object.assign(process.env, writerCredentials);
const events = [];
const service = new ReconcileService(db, scanner, (event) =>
events.push(event),
);
const bytes = Buffer.from('isolated reconciliation fixture');
const keys = [];
let user;
let chat;
let writer;
const originalStat = scanner.stat.bind(scanner);
function newKey() {
const key = `originals/${chat.id}/${randomUUID()}`;
keys.push(key);
return key;
}
function metadata(key) {
return {
chatId: chat.id,
ownerId: user.id,
objectKey: key,
filename: 'fixture.png',
contentType: 'image/png',
sizeBytes: bytes.length,
sha256: createHash('sha256').update(bytes).digest('hex'),
};
}
try {
await db.onModuleInit();
user = await db.user.create({
data: {
username: `rc_${randomUUID().replaceAll('-', '').slice(0, 20)}`,
displayName: 'Reconciliation test',
},
});
chat = await db.chat.create({
data: {
title: 'Isolated reconciliation fixtures',
members: { create: { userId: user.id, position: 0 } },
},
});
const prefix = `originals/${chat.id}/`;
const options = { apply: true, graceSeconds: 2, prefix };
const published = newKey();
await storage.put(published, bytes, 'image/png');
await db.attachment.create({ data: metadata(published) });
const orphan = newKey();
// This is a separate Node process with its own DB transaction and S3 client.
const writerCode = `
const {PrismaService}=require('./dist/prisma/prisma.service.js');
const {StorageService}=require('./dist/Storage/storage.service.js');
const {tryAttachmentObjectLock,OBJECT_TRANSACTION}=require('./dist/Attachment/object-lock.js');
const db=new PrismaService(); const s3=new StorageService();
(async()=>{ await db.onModuleInit(); await db.$transaction(async tx=>{
if(!await tryAttachmentObjectLock(tx,process.env.RECONCILE_TEST_KEY)) throw Error('lock');
await s3.put(process.env.RECONCILE_TEST_KEY,Buffer.from('orphan fixture'),'image/png');
process.send('written');
await new Promise(()=>{setInterval(()=>{},1000)});
},OBJECT_TRANSACTION); })().catch(()=>process.exit(1));`;
writer = spawn(process.execPath, ['-e', writerCode], {
cwd: process.cwd(),
env: { ...process.env, RECONCILE_TEST_KEY: orphan },
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
});
const written = await Promise.race([
once(writer, 'message').then(([message]) => message),
once(writer, 'exit').then(() => {
throw new Error('writer exited before PUT');
}),
delay(15000, 'timeout', { ref: false }),
]);
assert.equal(written, 'written');
// Even when an object looks twenty minutes old, its active writer lock protects it.
const whileWriting = await service.run(
options,
new Date(Date.now() + 1200000),
);
assert.equal(whileWriting.lockedObjects, 1);
assert.equal(whileWriting.deletedObjects, 0);
assert.equal(
writer.exitCode,
null,
'writer unexpectedly exited before the simulated crash',
);
assert.equal(writer.signalCode, null);
writer.kill('SIGKILL');
await once(writer, 'exit');
writer = undefined;
assert.equal(
await db.attachment.findUnique({ where: { objectKey: orphan } }),
null,
);
const lateReference = newKey();
const renewed = newKey();
await storage.put(lateReference, bytes, 'image/png');
await storage.put(renewed, bytes, 'image/png');
await delay(3100);
// An actual refused DB connection must never turn into "metadata absent".
const url = new URL(process.env.DATABASE_URL);
url.port = '1';
const savedUrl = process.env.DATABASE_URL;
process.env.DATABASE_URL = url.toString();
const unavailable = new PrismaService();
process.env.DATABASE_URL = savedUrl;
try {
await assert.rejects(() =>
new ReconcileService(unavailable, scanner).run(options),
);
assert.ok(await storage.stat(orphan));
} finally {
await unavailable.onModuleDestroy();
}
const fresh = newKey();
await storage.put(fresh, bytes, 'image/png');
const scanTime = new Date();
let referenced = false;
let refreshed = false;
scanner.stat = async (key) => {
if (key === lateReference && !referenced) {
referenced = true;
// Simulate a metadata commit between the first DB lookup and the final check.
await db.attachment.create({ data: metadata(key) });
}
if (key === renewed && !refreshed) {
refreshed = true;
await storage.put(key, bytes, 'image/png');
}
return originalStat(key);
};
const dryRun = await service.run({ ...options, apply: false }, scanTime);
assert.equal(dryRun.orphanCandidates, 1);
assert.equal(dryRun.deletedObjects, 0);
assert.ok(await storage.stat(orphan));
const applied = await service.run(options, scanTime);
assert.equal(applied.deletedObjects, 1);
assert.equal(await storage.stat(orphan), null);
for (const key of [published, lateReference, renewed, fresh])
assert.ok(await storage.stat(key));
assert.equal((await service.run(options, scanTime)).deletedObjects, 0);
scanner.stat = originalStat;
const missing = newKey();
const missingRow = await db.attachment.create({ data: metadata(missing) });
const report = await service.run({ ...options, apply: false }, scanTime);
assert.equal(report.missingObjects, 1);
assert.ok(await db.attachment.findUnique({ where: { id: missingRow.id } }));
assert.ok(
events.some(
(event) =>
event.event === 'missing_object' &&
event.attachmentId === missingRow.id,
),
);
const cli = spawnSync(
process.execPath,
['dist/Attachment/reconcile.cli.js', '--dry-run', '--prefix', prefix],
{
encoding: 'utf8',
timeout: 30000,
env: { ...process.env, ...scannerCredentials },
},
);
assert.equal(
cli.status,
2,
'CLI must report missing bytes as an integrity incident',
);
const summary = cli.stdout
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line))
.find((line) => line.event === 'reconcile_summary');
assert.equal(summary.graceSeconds, 600);
assert.equal(summary.mode, 'dry-run');
assert.equal(summary.missingObjects, 1);
console.log(
'PASS: real writer crash, DB outage, dry-run, orphan deletion, active/fresh/referenced protection, repeat run and missing-object reporting.',
);
} finally {
if (writer && writer.exitCode === null && writer.signalCode === null) {
writer.kill('SIGKILL');
await once(writer, 'exit');
}
scanner.stat = originalStat;
for (const key of keys) await storage.remove(key);
if (chat) {
await db.attachment.deleteMany({ where: { chatId: chat.id } });
await db.chat.delete({ where: { id: chat.id } });
}
if (user) await db.user.delete({ where: { id: user.id } });
storage.onModuleDestroy();
scanner.onModuleDestroy();
await db.onModuleDestroy();
}
+88
View File
@@ -0,0 +1,88 @@
"""Verify two API replicas, published Swagger and attachment failover through Nginx."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, run
def docker(*args):
result = subprocess.run(['docker', *args], cwd=ROOT, capture_output=True, text=True)
check(result.returncode == 0, 'Docker operation failed: ' + args[0])
return result.stdout.strip()
def wait_both(client, actor, expected):
deadline = time.monotonic() + 90
observed = set()
while time.monotonic() < deadline:
try:
response = client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
observed.add(response['headers']['X-Instance-Id'])
if observed == expected:
return
except Failure:
pass
time.sleep(0.1)
raise Failure('both replicas did not become available through Nginx')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://localhost:8080')
args = parser.parse_args()
ids = docker('compose', 'ps', '-q', 'api').splitlines()
check(len(ids) == 2, 'expected exactly two running API replicas')
names = docker('inspect', '--format', '{{.Config.Hostname}}', *ids).splitlines()
containers = dict(zip(names, ids))
c = Client(args.base_url)
alice, bob, _, chat = c.bootstrap()
wait_both(c, alice, set(names))
contract = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf8'))
documented = set()
for _ in range(20):
response = c.call('GET', '/swagger-json')
document = json.loads(response['bytes'])
documented.add(response['headers']['X-Instance-Id'])
check(document['openapi'] == contract['openapi'], 'wrong OpenAPI version')
for path, methods in contract['paths'].items():
for method, operation in methods.items():
actual = document['paths'][path][method]
check(all(actual.get(key) == value for key, value in operation.items()),
'Swagger differs from contract: ' + method + ' ' + path)
check(actual['security'] == operation.get('security', contract.get('security', [])),
'Swagger security differs from contract')
for name, schema in contract['components']['schemas'].items():
check(document['components']['schemas'][name] == schema, 'Swagger schema differs: ' + name)
if documented == set(names):
break
check(documented == set(names), 'Swagger did not respond from both replicas')
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=alice, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
attachment = uploaded['json']
target = uploaded['headers']['X-Instance-Id']
key = uuid.uuid4().hex
message = c.message(alice, chat, '', key, [attachment['id']])['json']
try:
print('Stopping the replica that accepted the attachment.', flush=True)
docker('stop', containers[target])
downloaded = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
check(downloaded['headers']['X-Instance-Id'] != target, 'stopped replica answered')
check(downloaded['bytes'] == content, 'attachment changed after failover')
check(c.message(alice, chat, '', key, [attachment['id']])['json'] == message,
'idempotency replay changed on the surviving replica')
print('PASS: two replicas, canonical Swagger and attachment/idempotency failover.', flush=True)
finally:
docker('start', containers[target])
wait_both(c, alice, set(names))
if __name__ == '__main__':
run(main)
+43
View File
@@ -0,0 +1,43 @@
"""Run the isolated writer/scanner integration test without logging credentials."""
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parent.parent
def main():
result = subprocess.run(
['docker', 'compose', 'exec', '-T', 'reconciler', 'node', '-e',
'process.stdout.write(JSON.stringify({S3_ACCESS_KEY_ID:process.env.S3_ACCESS_KEY_ID,'
'S3_SECRET_ACCESS_KEY:process.env.S3_SECRET_ACCESS_KEY}))'],
cwd=ROOT, capture_output=True, text=True, check=True, timeout=30,
)
credentials = json.loads(result.stdout)
if not all(credentials.values()):
raise RuntimeError('Reconciler credentials are missing')
payload = json.dumps({
'credentials': credentials,
'source': (ROOT / 'test/reconcile.mjs').read_text(encoding='utf-8'),
})
loader = (
"let input='';for await(const chunk of process.stdin)input+=chunk;"
"const {source,credentials}=JSON.parse(input);"
"process.env.RECONCILE_TEST_SCANNER_CREDENTIALS=JSON.stringify(credentials);"
"await import('data:text/javascript;base64,'+"
"Buffer.from(source+'\\n//# sourceURL=reconcile.integration.mjs').toString('base64'));"
)
return subprocess.run(
['docker', 'compose', 'exec', '-T', '--index', '1', 'api',
'node', '--input-type=module', '-e', loader],
cwd=ROOT, input=payload, text=True, timeout=120,
).returncode
if __name__ == '__main__':
try:
sys.exit(main())
except (subprocess.SubprocessError, ValueError, RuntimeError) as error:
print(f'Reconciliation test could not run: {type(error).__name__}', file=sys.stderr)
sys.exit(1)
+91
View File
@@ -0,0 +1,91 @@
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import {
S3Client,
PutObjectCommand,
CopyObjectCommand,
GetObjectCommand,
DeleteObjectCommand,
} from '@aws-sdk/client-s3';
import { bootstrapSettings } from '../infra/rustfs/policies.mjs';
const config = bootstrapSettings();
const client = new S3Client({
endpoint: config.endpoint,
region: config.region,
forcePathStyle: true,
credentials: config.api,
maxAttempts: 1,
});
const chat = randomUUID();
const source = `staging/${chat}/${randomUUID()}`;
const invalid = `staging/${chat}/${randomUUID()}`;
const original = `originals/${chat}/${randomUUID()}`;
const data = Buffer.from('conditional direct upload fixture');
const checksum = (value) => createHash('sha256').update(value).digest('base64');
const send = (Command, value) =>
client.send(new Command({ Bucket: config.bucket, ...value }), {
abortSignal: AbortSignal.timeout(15000),
});
try {
const put = await send(PutObjectCommand, {
Key: source,
Body: data,
ContentType: 'image/png',
IfNoneMatch: '*',
ChecksumSHA256: checksum(data),
});
await assert.rejects(
() =>
send(PutObjectCommand, {
Key: source,
Body: data,
IfNoneMatch: '*',
ChecksumSHA256: checksum(data),
}),
(error) => error.$metadata?.httpStatusCode === 412,
'Pinned RustFS must enforce create-only PUT',
);
await assert.rejects(
() =>
send(PutObjectCommand, {
Key: invalid,
Body: data,
ChecksumSHA256: Buffer.alloc(32).toString('base64'),
}),
(error) => error.$metadata?.httpStatusCode === 400,
'Pinned RustFS must validate the uploaded checksum',
);
await assert.rejects(
() =>
send(CopyObjectCommand, {
Key: original,
CopySource: `${config.bucket}/${source}`,
CopySourceIfMatch: '"wrong"',
}),
(error) => error.$metadata?.httpStatusCode === 412,
'Pinned RustFS must reject changed copy sources',
);
await send(CopyObjectCommand, {
Key: original,
CopySource: `${config.bucket}/${source}`,
CopySourceIfMatch: put.ETag,
});
const value = await send(GetObjectCommand, { Key: original });
assert.equal(await value.Body.transformToString(), data.toString());
const anonymous = await fetch(
`${config.endpoint}/${config.bucket}/${original}`,
);
assert.equal(anonymous.status, 403);
await anonymous.body?.cancel();
console.log(
'PASS: RustFS 1.0.4 enforces If-None-Match, SHA-256 and conditional server-side copy',
);
} finally {
await Promise.all(
[source, invalid, original].map((Key) =>
send(DeleteObjectCommand, { Key }),
),
);
client.destroy();
}
+140
View File
@@ -0,0 +1,140 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import * as s3 from '@aws-sdk/client-s3';
import { adminRequest } from '../infra/rustfs/admin.mjs';
import { bootstrapSettings } from '../infra/rustfs/policies.mjs';
const settings = bootstrapSettings();
const Bucket = settings.bucket;
const clients = Object.fromEntries(
['root', 'api', 'reconciler'].map((role) => [
role,
new s3.S3Client({
endpoint: settings.endpoint,
region: settings.region,
forcePathStyle: true,
maxAttempts: 1,
credentials: role === 'root' ? settings.credentials : settings[role],
}),
]),
);
const id = randomUUID();
const Key = `originals/iam-test/${id}`;
const outside = `iam-test/${id}`;
const otherBucket = `iam-test-${id}`;
const send = (role, Command, args = {}) =>
clients[role].send(new Command({ Bucket, ...args }), {
abortSignal: AbortSignal.timeout(30000),
});
async function denied(action) {
await assert.rejects(
action,
(error) => error.$metadata?.httpStatusCode === 403 || error.status === 403,
);
}
let failed = false;
try {
await send('root', s3.CreateBucketCommand, { Bucket: otherBucket });
await send('root', s3.PutObjectCommand, { Key: outside, Body: 'private' });
await send('root', s3.PutObjectCommand, {
Bucket: otherBucket,
Key,
Body: 'private',
});
await send('api', s3.PutObjectCommand, { Key, Body: 'fixture' });
for (const role of ['api', 'reconciler']) {
await send(role, s3.GetBucketLocationCommand);
await send(role, s3.HeadObjectCommand, { Key });
const object = await send(role, s3.GetObjectCommand, { Key });
assert.equal(await object.Body.transformToString(), 'fixture');
// RustFS filters ListBuckets to accessible buckets instead of returning 403.
const visible = await send(role, s3.ListBucketsCommand);
assert.ok(
!(visible.Buckets ?? []).some((bucket) => bucket.Name === otherBucket),
);
await denied(() => send(role, s3.GetObjectCommand, { Key: outside }));
await denied(() =>
send(role, s3.PutObjectCommand, { Key: outside, Body: 'denied' }),
);
await denied(() => send(role, s3.DeleteObjectCommand, { Key: outside }));
await denied(() =>
send(role, s3.GetObjectCommand, { Bucket: otherBucket, Key }),
);
await denied(() => send(role, s3.GetBucketPolicyCommand));
await denied(() =>
adminRequest(
{ ...settings, credentials: settings[role] },
'GET',
'list-users',
),
);
await denied(() =>
adminRequest(
{ ...settings, credentials: settings[role] },
'PUT',
'add-user',
{ accessKey: `DENIED${id.replaceAll('-', '')}` },
{ secretKey: randomUUID(), status: 'enabled' },
),
);
console.log(
`PASS: ${role}: object read and readiness allowed; other prefixes/buckets, bucket policy and admin denied`,
);
}
await denied(() =>
send('api', s3.ListObjectsV2Command, { Prefix: 'originals/' }),
);
await denied(() =>
send('reconciler', s3.PutObjectCommand, { Key, Body: 'denied' }),
);
await denied(() => send('reconciler', s3.ListObjectsV2Command));
await denied(() =>
send('reconciler', s3.ListObjectsV2Command, { Prefix: 'iam-test/' }),
);
const listed = await send('reconciler', s3.ListObjectsV2Command, {
Prefix: `originals/iam-test/${id}`,
});
assert.ok(listed.Contents.some((object) => object.Key === Key));
await send('reconciler', s3.ListObjectsV2Command, {
Prefix: 'originals/',
MaxKeys: 1,
});
await send('reconciler', s3.DeleteObjectCommand, { Key });
await send('api', s3.PutObjectCommand, { Key, Body: 'fixture' });
await send('api', s3.DeleteObjectCommand, { Key });
await assert.rejects(
() => send('reconciler', s3.HeadObjectCommand, { Key }),
(error) => error.$metadata?.httpStatusCode === 404,
'Reconciler must distinguish missing bytes from authorization failures',
);
const anonymous = await fetch(`${settings.endpoint}/${Bucket}/${outside}`);
assert.equal(anonymous.status, 403);
await anonymous.body?.cancel();
console.log(
'PASS: API CRUD without listing; reconciler scoped listing/HEAD/delete without PUT; anonymous access denied',
);
} catch (error) {
failed = true;
throw error;
} finally {
const cleanup = await Promise.allSettled([
send('root', s3.DeleteObjectCommand, { Key }),
send('root', s3.DeleteObjectCommand, { Key: outside }),
send('root', s3.DeleteObjectCommand, { Bucket: otherBucket, Key }),
]);
cleanup.push(
...(await Promise.allSettled([
send('root', s3.DeleteBucketCommand, { Bucket: otherBucket }),
])),
);
for (const client of Object.values(clients)) client.destroy();
const errors = cleanup.filter(
(result) =>
result.status === 'rejected' &&
result.reason.$metadata?.httpStatusCode !== 404,
);
if (errors.length) {
console.error(`IAM fixture cleanup failed: ${id}`);
if (!failed) throw new Error('IAM fixture cleanup failed');
}
}
+131
View File
@@ -0,0 +1,131 @@
// One fresh process per input/cache/size combination. Executes the real validator.
import { createRequire } from 'node:module';
import { readFile, copyFile, mkdtemp, rm, rmdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import {
setTimeout as delay,
setImmediate as tick,
} from 'node:timers/promises';
import { performance } from 'node:perf_hooks';
import assert from 'node:assert/strict';
const require = createRequire(`${process.cwd()}/package.json`);
const sharp = require('sharp');
const {
AttachmentService,
} = require('./dist/Attachment/attachment.service.js');
const [source, inputMode, cacheMode] = process.argv.slice(2);
assert.ok(['buffer', 'file'].includes(inputMode));
assert.ok(['default', 'off'].includes(cacheMode));
assert.equal(typeof global.gc, 'function');
if (cacheMode === 'off') sharp.cache(false);
const validator = new AttachmentService(null, null);
const snapshot = () => ({ ...process.memoryUsage(), sharp: sharp.cache() });
const directory = await mkdtemp(join(tmpdir(), 'sharp-profile-'));
let currentFile;
let active;
const sample = () => {
if (!active) return;
const memory = process.memoryUsage();
for (const key of Object.keys(memory))
active.peak[key] = Math.max(active.peak[key], memory[key]);
active.samples++;
const now = performance.now();
active.maxSampleGapMs = Math.max(
active.maxSampleGapMs,
now - active.lastSample,
);
active.lastSample = now;
};
const timer = setInterval(sample, 20);
timer.unref();
let sequence = 0;
async function validate(measure) {
const before = snapshot();
active = measure
? {
peak: { ...process.memoryUsage() },
samples: 0,
lastSample: performance.now(),
maxSampleGapMs: 0,
}
: undefined;
const started = performance.now();
let input;
try {
if (inputMode === 'file') {
// Real complete uses a unique temporary path for every upload, then unlinks it.
currentFile = join(directory, `${sequence++}.png`);
await copyFile(source, currentFile);
input = currentFile;
} else input = await readFile(source);
sample();
const afterInput = snapshot();
await validator.validateImage(input, 'image/png');
sample();
const afterValidation = snapshot();
input = null;
if (currentFile) {
await rm(currentFile);
currentFile = undefined;
}
sample();
const result = measure
? {
before,
afterInput,
afterValidation,
afterRelease: snapshot(),
peak: active.peak,
samples: active.samples,
maxSampleGapMs: active.maxSampleGapMs,
elapsedMs: performance.now() - started,
}
: undefined;
active = undefined;
return result;
} finally {
input = null;
}
}
try {
for (let i = 0; i < 4; i++) await validate(false);
const baseline = snapshot();
const uploads = [];
for (let i = 0; i < 3; i++) uploads.push(await validate(true));
const afterSeries = snapshot();
await delay(1000);
const afterIdle = snapshot();
// Diagnostic only: do not force GC during the measured series.
global.gc();
await tick();
global.gc();
await tick();
const afterGc = snapshot();
sharp.cache(false);
global.gc();
await tick();
const afterCacheClear = snapshot();
console.log(
JSON.stringify({
status: 'passed',
inputMode,
cacheMode,
intervalMs: 20,
nodeVersion: process.version,
sharpVersions: sharp.versions,
warmups: 4,
baseline,
uploads,
afterSeries,
afterIdle,
afterGc,
afterCacheClear,
}),
);
} finally {
clearInterval(timer);
if (currentFile) await rm(currentFile, { force: true });
await rmdir(directory);
}
+50
View File
@@ -0,0 +1,50 @@
"""Isolate the actual Sharp validator: Buffer/file input, operation cache on/off."""
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from direct_client import ROOT, Failure, check, docker
spec = importlib.util.spec_from_file_location('upload_metrics', ROOT / 'test/concurrent-uploads.py')
metrics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(metrics)
def main():
report = {'status': 'failed', 'cases': [], 'method': 'Fresh Node process per case, real AttachmentService.validateImage; 4 warm-ups, 3 measured operations; unique file paths; post-series GC and cache clearing are diagnostics only. RSS is not comparable to a full API process.'}
try:
with tempfile.TemporaryDirectory(prefix='sharp-memory-', dir=ROOT / 'evidence') as directory:
for side in [512, 1792]:
path = Path(directory) / 'image.png'
image = metrics.png_image(side) + metrics.chunk(b'IEND', b'')
path.write_bytes(image)
for round_number in [1, 2]:
for cache in (['default', 'off'] if round_number == 1 else ['off', 'default']):
for mode in (['buffer', 'file'] if round_number == 1 else ['file', 'buffer']):
output = docker('compose', 'run', '--rm', '--no-deps', '-T',
'-e', 'UPLOAD_MEMORY_PROFILE=0',
'-v', f'{directory}:/profile-input:ro',
'-v', f'{ROOT / "test/sharp-memory-profile.mjs"}:/app/test/sharp-memory-profile.mjs:ro',
'--entrypoint', 'node', 'api', '--expose-gc',
'test/sharp-memory-profile.mjs', '/profile-input/image.png', mode, cache)
result = json.loads(output)
check(result['status'] == 'passed' and len(result['uploads']) == 3, 'Validator profile failed')
report['cases'].append({'round': round_number, 'sidePixels': side, 'fileBytes': len(image), **result})
print(f'PASS: round {round_number}, {side}px, {mode}, cache={cache}', flush=True)
report['status'] = 'passed'
except BaseException as error:
report['errorType'] = type(error).__name__
raise
finally:
(ROOT / 'evidence/sharp-memory-profile.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+254
View File
@@ -0,0 +1,254 @@
// Executed inside reconciler: read-only DB/S3 inspection; uploads use HTTP API credentials.
import assert from 'node:assert/strict';
import http from 'node:http';
import { createHash } from 'node:crypto';
import { createRequire } from 'node:module';
import { setTimeout as delay } from 'node:timers/promises';
let input = '';
for await (const part of process.stdin) input += part;
const fixture = JSON.parse(input);
const image = Buffer.from(fixture.image, 'base64');
const require = createRequire(`${process.cwd()}/package.json`);
const { PrismaService } = require('./dist/prisma/prisma.service.js');
const { StorageService } = require('./dist/Storage/storage.service.js');
const db = new PrismaService();
const storage = new StorageService();
const prefix = `originals/${fixture.chatId}/`;
const reports = [];
let phase = 'startup';
function call(url, { method = 'GET', body, token = fixture.ownerToken } = {}) {
return new Promise((resolve, reject) => {
const req = http.request(
url,
{
method,
headers: {
Authorization: `Bearer ${token}`,
...(body
? { 'Content-Type': 'image/png', 'Content-Length': body.length }
: {}),
},
},
(res) => {
const parts = [];
res.on('data', (part) => parts.push(part));
res.on('end', () =>
resolve({
status: res.statusCode,
body: Buffer.concat(parts),
headers: res.headers,
}),
);
res.on('error', reject);
},
);
req.on('error', reject);
req.setTimeout(10000, () => req.destroy(new Error('HTTP probe timed out')));
req.end(body);
});
}
async function contents(expected) {
const rows = await db.attachment.findMany({
where: { chatId: fixture.chatId },
select: { objectKey: true },
});
const keys = [];
for await (const object of storage.objects(prefix)) keys.push(object.key);
assert.equal(rows.length, expected, 'interrupted request created metadata');
assert.equal(keys.length, expected, 'interrupted request left an S3 object');
assert.deepEqual(keys.sort(), rows.map((row) => row.objectKey).sort());
}
async function abort(url, chunked) {
await new Promise((resolve, reject) => {
const req = http.request(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${fixture.ownerToken}`,
'Content-Type': 'image/png',
...(chunked ? {} : { 'Content-Length': image.length + 1000 }),
},
});
let intentional = false;
req.on('error', (error) => {
if (!intentional) reject(error);
});
req.on('response', (res) => {
res.resume();
reject(new Error('partial upload responded before client abort'));
});
req.setTimeout(5000, () =>
req.destroy(new Error('partial write timed out')),
);
// Valid PNG bytes, but incomplete HTTP framing: neither Content-Length nor chunk terminator is satisfied.
req.write(image, () => {
void delay(200).then(() => {
intentional = true;
req.destroy();
resolve();
});
});
});
}
async function deadline(url, timeoutMs, direct) {
const started = performance.now();
const response = await new Promise((resolve, reject) => {
let timer;
let watchdog;
const req = http.request(
url,
{
method: 'POST',
headers: {
Authorization: `Bearer ${fixture.ownerToken}`,
'Content-Type': 'image/png',
'Content-Length': image.length + 100000,
},
},
(res) => {
clearInterval(timer);
const parts = [];
res.on('data', (part) => parts.push(part));
res.on('error', (error) => {
clearTimeout(watchdog);
reject(error);
});
res.on('end', () => {
clearTimeout(watchdog);
req.destroy();
resolve({
status: res.statusCode,
body: Buffer.concat(parts),
headers: res.headers,
});
});
},
);
req.on('error', (error) => {
clearInterval(timer);
clearTimeout(watchdog);
reject(error);
});
watchdog = setTimeout(
() => req.destroy(new Error('upload deadline did not fire')),
timeoutMs + 8000,
);
req.write(image.subarray(0, 16));
timer = setInterval(() => req.write(Buffer.from([0])), 200);
});
const elapsedMs = performance.now() - started;
assert.equal(response.status, 408);
assert.match(response.headers['content-type'], /^application\/json/);
const error = JSON.parse(response.body).error;
assert.equal(error.code, 'invalid_request');
assert.equal(error.request_id, response.headers['x-request-id']);
assert.ok(error.request_id && response.headers['x-instance-id']);
// Connection is hop-by-hop: Nginx owns the frontend keep-alive policy.
if (direct) assert.equal(response.headers.connection, 'close');
assert.ok(
elapsedMs >= timeoutMs - 300 && elapsedMs < timeoutMs + 7000,
'unexpected upload deadline duration',
);
return {
status: response.status,
elapsedMs: Math.round(elapsedMs),
instance: response.headers['x-instance-id'],
connection: response.headers.connection,
};
}
try {
await db.onModuleInit();
await contents(0);
let expected = 0;
for (const target of fixture.targets) {
phase = target.name;
const url = `${target.url}/api/v1/chats/${fixture.chatId}/attachments?filename=interruption.png`;
const control = await call(url, { method: 'POST', body: image });
assert.equal(control.status, 201);
const attachment = JSON.parse(control.body);
assert.equal(
attachment.sha256,
createHash('sha256').update(image).digest('hex'),
);
expected++;
await contents(expected);
for (const chunked of [false, true]) {
phase = `${target.name}:${chunked ? 'chunked' : 'content-length'}-abort`;
await abort(url, chunked);
await delay(300);
await contents(expected);
}
phase = `${target.name}:deadline`;
const timedOut = await deadline(
url,
target.timeoutMs,
target.name !== 'nginx',
);
await delay(300);
await contents(expected);
phase = `${target.name}:recovery`;
const recovery = await call(url, { method: 'POST', body: image });
assert.equal(recovery.status, 201);
expected++;
const downloaded = await call(
`${target.url}/api/v1/attachments/${JSON.parse(recovery.body).id}/content`,
{ token: fixture.readerToken },
);
assert.equal(downloaded.status, 200);
assert.deepEqual(downloaded.body, image);
await contents(expected);
reports.push({
target: target.name,
contentLengthAbort: 'passed',
chunkedAbort: 'passed',
deadline: timedOut,
normalUploadAfterAbort: 'passed',
databaseAndS3Match: true,
});
console.log(
`PASS: ${target.name}: both client aborts leave no bytes/metadata; slow upload gets 408; next upload/download succeeds`,
);
}
console.log(
JSON.stringify({
event: 'upload_interruption_summary',
status: 'passed',
targets: reports,
}),
);
} catch (error) {
console.log(
JSON.stringify({
event: 'upload_interruption_summary',
status: 'failed',
phase,
errorType: error.name,
assertion:
error.code === 'ERR_ASSERTION'
? {
message: error.message.split('\n')[0],
actual: ['number', 'boolean', 'string'].includes(
typeof error.actual,
)
? String(error.actual).slice(0, 80)
: undefined,
expected: ['number', 'boolean', 'string'].includes(
typeof error.expected,
)
? String(error.expected).slice(0, 80)
: undefined,
}
: undefined,
targets: reports,
}),
);
process.exitCode = 1;
} finally {
storage.onModuleDestroy();
await db.onModuleDestroy();
}
+82
View File
@@ -0,0 +1,82 @@
"""Exercise real HTTP client aborts and total receive deadlines, then inspect DB/S3."""
import argparse
import base64
import json
from pathlib import Path
import subprocess
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check
def docker(*args, **kwargs):
return subprocess.run(['docker', *args], cwd=ROOT, capture_output=True,
text=True, check=True, timeout=180, **kwargs).stdout
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--targets', choices=['all', 'nginx', 'api'], default='all')
args = parser.parse_args()
client = Client('http://127.0.0.1:8080', timeout=10)
run_id = str(uuid.uuid4())
actors, chat = [], None
report = {'status': 'failed'}
try:
containers = docker('compose', 'ps', '-q', 'api').split()
check(len(containers) == 2, 'Expected two API replicas')
states = json.loads(docker('inspect', *containers))
targets = []
for state in states:
env = dict(item.split('=', 1) for item in state['Config']['Env'] if '=' in item)
timeout_ms = int(env.get('UPLOAD_BODY_TIMEOUT_MS', '15000'))
address = next(iter(state['NetworkSettings']['Networks'].values()))['IPAddress']
targets.append({'name': state['Config']['Hostname'], 'url': 'http://' + address + ':8080', 'timeoutMs': timeout_ms})
check(len({target['timeoutMs'] for target in targets}) == 1, 'API receive deadlines differ')
targets.append({'name': 'nginx', 'url': 'http://nginx', 'timeoutMs': targets[0]['timeoutMs']})
if args.targets != 'all':
targets = [target for target in targets if (target['name'] == 'nginx') == (args.targets == 'nginx')]
for suffix in ['a', 'b']:
actors.append(client.user('cu' + run_id[:8] + suffix))
chat = client.call('POST', '/api/v1/chats', 201, actor=actors[0], schema='Chat',
body={'title': 'upload-interruption:' + run_id, 'member_ids': [actor['id'] for actor in actors]})['json']
payload = {'chatId': chat['id'], 'ownerToken': actors[0]['token'], 'readerToken': actors[1]['token'],
'image': base64.b64encode((ROOT / 'tests/fixtures/sample.png').read_bytes()).decode(), 'targets': targets}
source = (ROOT / 'test/upload-interruption.mjs').read_text(encoding='utf-8')
result = subprocess.run(['docker', 'compose', 'exec', '-T', 'reconciler', 'node', '--input-type=module', '-e', source],
cwd=ROOT, input=json.dumps(payload), text=True, capture_output=True,
timeout=sum(target['timeoutMs'] for target in targets) / 1000 + 120)
for line in result.stdout.splitlines():
if line.startswith('{'):
item = json.loads(line)
if item.get('event') == 'upload_interruption_summary':
report = item
elif line.startswith('PASS:'):
print(line, flush=True)
check(result.returncode == 0 and report.get('status') == 'passed', 'Upload interruption test failed; see evidence/upload-interruption.json')
finally:
try:
source = (ROOT / 'test/concurrent-cleanup.mjs').read_text(encoding='utf-8')
payload = {'runId': run_id, 'chatId': chat['id'] if chat else None,
'userIds': [actor['id'] for actor in actors], 'kind': 'upload-interruption'}
docker('compose', 'exec', '-T', '--index', '1', 'api', 'node', '--input-type=module', '-e', source, input=json.dumps(payload))
report['fixturesRemoved'] = True
except (OSError, subprocess.SubprocessError):
report['fixturesRemoved'] = False
if report['status'] == 'passed':
report['status'] = 'failed'
raise Failure('Upload interruption fixture cleanup failed') from None
finally:
(ROOT / 'evidence/upload-interruption.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('PASS: upload interruption and receive deadline; targets=' + args.targets + '; fixtures removed')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError, subprocess.SubprocessError) as error:
print('FAIL: ' + (str(error) if isinstance(error, Failure) else type(error).__name__), file=sys.stderr)
sys.exit(1)
+147
View File
@@ -0,0 +1,147 @@
// Executed by the test through docker exec; does not change the API process.
import { readFileSync, readdirSync } from 'node:fs';
import { createInterface } from 'node:readline';
import { performance } from 'node:perf_hooks';
const emit = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);
const candidates = readdirSync('/proc').filter((name) => {
if (!/^\d+$/.test(name) || Number(name) === process.pid) return false;
try {
const args = readFileSync(`/proc/${name}/cmdline`, 'utf8').split('\0');
return args.some((arg) => /(^|\/)dist\/main\.js$/.test(arg));
} catch {
return false;
}
});
if (candidates.length !== 1)
throw new Error('Expected exactly one API process');
const pid = Number(candidates[0]);
const startTime = () =>
readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ').at(-1).split(' ')[19];
const identity = startTime();
function snapshot() {
if (startTime() !== identity)
throw new Error('API process changed during test');
const status = readFileSync(`/proc/${pid}/status`, 'utf8');
const rss = Number(status.match(/^VmRSS:\s+(\d+) kB$/m)?.[1]) * 1024;
const hwm = Number(status.match(/^VmHWM:\s+(\d+) kB$/m)?.[1]) * 1024;
if (!Number.isFinite(rss) || !Number.isFinite(hwm))
throw new Error('Missing RSS/HWM metrics');
const events = Object.fromEntries(
readFileSync('/sys/fs/cgroup/memory.events', 'utf8')
.trim()
.split('\n')
.map((line) => {
const [key, value] = line.split(' ');
return [key, Number(value)];
}),
);
let rx = 0;
let tx = 0;
for (const line of readFileSync('/proc/net/dev', 'utf8')
.split('\n')
.slice(2)) {
if (!line.includes(':')) continue;
const [name, counters] = line.split(':');
if (name.trim() === 'lo') continue;
const values = counters.trim().split(/\s+/).map(Number);
rx += values[0];
tx += values[8];
}
const cgroup = Number(
readFileSync('/sys/fs/cgroup/memory.current', 'utf8').trim(),
);
return {
rss,
hwm,
oom: events.oom,
oomKill: events.oom_kill,
rx,
tx,
cgroup,
};
}
let active;
function sample() {
const value = snapshot();
if (active) {
active.peakRss = Math.max(active.peakRss, value.rss);
active.peakCgroup = Math.max(active.peakCgroup, value.cgroup);
active.maxSampleGapMs = Math.max(
active.maxSampleGapMs,
performance.now() - active.lastSample,
);
active.lastSample = performance.now();
active.samples++;
}
return value;
}
const timer = setInterval(() => {
if (!active) return;
try {
sample();
} catch {
emit({
event: 'error',
message: 'API memory probe failed; process may have restarted',
});
process.exit(1);
}
}, 50);
const input = createInterface({ input: process.stdin });
input.on('line', (command) => {
try {
if (command === 'begin') {
if (active) throw new Error('Memory phase already active');
const baseline = snapshot();
active = {
baseline,
peakRss: baseline.rss,
peakCgroup: baseline.cgroup,
samples: 0,
started: performance.now(),
lastSample: performance.now(),
maxSampleGapMs: 0,
};
emit({ event: 'begin', pid });
} else if (command === 'end') {
if (!active) throw new Error('No memory phase active');
const end = sample();
emit({
event: 'summary',
pid,
baselineRssBytes: active.baseline.rss,
sampledPeakRssBytes: active.peakRss,
finalRssBytes: end.rss,
baselineCgroupBytes: active.baseline.cgroup,
sampledPeakCgroupBytes: active.peakCgroup,
finalCgroupBytes: end.cgroup,
lifetimeHwmBeforeBytes: active.baseline.hwm,
lifetimeHwmAfterBytes: end.hwm,
oomDelta: end.oom - active.baseline.oom,
oomKillDelta: end.oomKill - active.baseline.oomKill,
networkRxBytes: end.rx - active.baseline.rx,
networkTxBytes: end.tx - active.baseline.tx,
samples: active.samples,
maxSampleGapMs: active.maxSampleGapMs,
durationMs: performance.now() - active.started,
});
active = undefined;
} else if (command === 'snapshot') {
emit({ event: 'snapshot', ...snapshot() });
} else if (command === 'quit') {
input.close();
process.stdin.destroy();
} else throw new Error('Unknown memory probe command');
} catch {
emit({ event: 'error', message: 'Memory probe command failed' });
process.exit(1);
}
});
input.on('close', () => clearInterval(timer));
emit({
event: 'ready',
pid,
instance: readFileSync('/etc/hostname', 'utf8').trim(),
intervalMs: 50,
});
+119
View File
@@ -0,0 +1,119 @@
// Run as a temporary docker-exec client. Secrets and signed URLs arrive only on stdin.
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import http from 'node:http';
let input = '';
for await (const chunk of process.stdin) input += chunk;
const { targets, owner, reader, chat, imageBase64, mode } = JSON.parse(input);
const image = Buffer.from(imageBase64, 'base64');
const digest = createHash('sha256').update(image).digest('hex');
assert.ok(['proxy', 'direct'].includes(mode));
assert.equal(targets.length, 2);
async function signedPut(capability) {
const signed = new URL(capability.url);
// Connect to the same Nginx PUT listener inside Docker, preserving the signed Host.
const status = await new Promise((resolve, reject) => {
const request = http.request(
{
hostname: 'nginx',
port: 9000,
method: 'PUT',
path: signed.pathname + signed.search,
headers: { ...capability.headers, Host: signed.host },
timeout: 60000,
},
(response) => {
response.resume();
response.once('end', () => resolve(response.statusCode));
response.once('error', reject);
},
);
request.once('timeout', () =>
request.destroy(new Error('Warm PUT timed out')),
);
request.once('error', reject);
request.end(image);
});
assert.equal(status, 200, 'Warm PUT failed');
}
const counts = {};
for (const target of targets) {
assert.match(target.address, /^\d{1,3}(\.\d{1,3}){3}$/);
const base = `http://${target.address}:8080`;
async function call(path, token, options = {}, expected = 200) {
const response = await fetch(base + path, {
...options,
headers: { Authorization: `Bearer ${token}`, ...options.headers },
signal: AbortSignal.timeout(60000),
});
assert.equal(response.status, expected, 'Warm API request failed');
assert.equal(
response.headers.get('x-instance-id'),
target.instance,
'Warm-up reached a different API',
);
return response;
}
for (let index = 0; index < 2; index++) {
let response;
if (mode === 'proxy') {
response = await call(
`/api/v1/chats/${chat.id}/attachments?filename=warmup.png`,
owner.token,
{
method: 'POST',
headers: { 'Content-Type': 'image/png' },
body: image,
},
201,
);
} else {
const capability = await (
await call(
`/api/v1/chats/${chat.id}/attachment-uploads`,
owner.token,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: 'warmup.png',
content_type: 'image/png',
size_bytes: image.length,
sha256: digest,
}),
},
201,
)
).json();
await signedPut(capability);
response = await call(
capability.complete_url,
owner.token,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{}',
},
201,
);
}
const attachment = await response.json();
assert.equal(attachment.sha256, digest);
assert.equal(attachment.size_bytes, image.length);
const meta = await (
await call(`/api/v1/attachments/${attachment.id}`, reader.token)
).json();
assert.deepEqual(meta, attachment);
const downloaded = Buffer.from(
await (
await call(`/api/v1/attachments/${attachment.id}/content`, reader.token)
).arrayBuffer(),
);
assert.deepEqual(downloaded, image);
counts[target.instance] = (counts[target.instance] ?? 0) + 1;
}
}
console.log(JSON.stringify({ counts, verifiedDownloads: 4 }));