forked from mtusi2026/mtusi2026lab4
feat: add s3 readiness and orphan object reconciler
This commit is contained in:
+1
-1
@@ -40,6 +40,6 @@ USER node
|
|||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \
|
HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \
|
||||||
CMD node -e "require('http').get('http://127.0.0.1:8080/health/ready',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
|
CMD node -e "require('http').get('http://127.0.0.1:8080/health/core',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
|
||||||
|
|
||||||
CMD ["node", "dist/main.js"]
|
CMD ["node", "dist/main.js"]
|
||||||
|
|||||||
+30
-2
@@ -10,7 +10,7 @@ services:
|
|||||||
- -ec
|
- -ec
|
||||||
- |
|
- |
|
||||||
cd /secrets
|
cd /secrets
|
||||||
mkdir -p postgres redis api migrate s3 s3-init
|
mkdir -p postgres redis api migrate s3 s3-init reconciler
|
||||||
for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20; do
|
for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20; do
|
||||||
file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:}
|
file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:}
|
||||||
[ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file"
|
[ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file"
|
||||||
@@ -20,7 +20,8 @@ services:
|
|||||||
printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" > api/database_url
|
printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" > api/database_url
|
||||||
printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url
|
printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url
|
||||||
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url
|
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url
|
||||||
chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/*
|
cp api/database_url api/s3_access_key_id api/s3_secret_access_key reconciler/
|
||||||
|
chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/*
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
limits: { cpus: "0.1", memory: 32M }
|
limits: { cpus: "0.1", memory: 32M }
|
||||||
@@ -175,6 +176,33 @@ services:
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
reconciler:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
target: runtime
|
||||||
|
image: mtusi-messenger-lab4-api:dev
|
||||||
|
command: ["node", "dist/reconcile.js", "--apply", "--loop", "--grace-seconds=${RECONCILE_GRACE_SECONDS:-3600}", "--interval-seconds=${RECONCILE_INTERVAL_SECONDS:-300}"]
|
||||||
|
environment:
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
S3_ENDPOINT: http://s3:9000
|
||||||
|
S3_REGION: ${S3_REGION:-us-east-1}
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||||
|
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||||
|
volumes:
|
||||||
|
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: reconciler } }
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.25", memory: 128M }
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
lb:
|
lb:
|
||||||
image: haproxy:3.0.6-alpine
|
image: haproxy:3.0.6-alpine
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ frontend public
|
|||||||
backend api
|
backend api
|
||||||
balance roundrobin
|
balance roundrobin
|
||||||
http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ }
|
http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ }
|
||||||
option httpchk GET /health/ready
|
option httpchk GET /health/core
|
||||||
http-check expect status 200
|
http-check expect status 200
|
||||||
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
||||||
server-template api 1-4 api:8080
|
server-template api 1-4 api:8080
|
||||||
|
|||||||
Executable
+39
@@ -0,0 +1,39 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||||
|
key="attachments/orphan-$(date +%s)"
|
||||||
|
|
||||||
|
mc_api() {
|
||||||
|
docker compose run --rm --no-deps -T -e BUCKET="$bucket" -e KEY="$key" --entrypoint sh s3-init -c "
|
||||||
|
cd /run/secrets
|
||||||
|
export MC_HOST_api=\"http://\$(cat s3_access_key_id):\$(cat s3_secret_access_key)@s3:9000\"
|
||||||
|
$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
run() {
|
||||||
|
docker compose run --rm --no-deps -T reconciler node dist/reconcile.js "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "## Отказ между S3 и БД: объект есть, строки нет"
|
||||||
|
mc_api 'echo orphan > /tmp/o && mc cp -q /tmp/o "api/$BUCKET/$KEY" >/dev/null && mc stat "api/$BUCKET/$KEY" | head -1'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "## Свежий объект, grace 3600 с, --apply: не удалён"
|
||||||
|
run --apply --grace-seconds=3600
|
||||||
|
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null && echo "объект на месте"'
|
||||||
|
|
||||||
|
sleep 3
|
||||||
|
echo
|
||||||
|
echo "## Dry-run, grace 1 с: найден, не удалён"
|
||||||
|
run --grace-seconds=1
|
||||||
|
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null && echo "объект на месте"'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "## --apply, grace 1 с: удалён только он"
|
||||||
|
run --apply --grace-seconds=1
|
||||||
|
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null 2>&1 && echo "объект всё ещё есть" || echo "объект удалён"'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "## Повторный запуск: удалять нечего"
|
||||||
|
run --apply --grace-seconds=1
|
||||||
Executable
+79
@@ -0,0 +1,79 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import hashlib
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / 'tests'))
|
||||||
|
from client import Client
|
||||||
|
|
||||||
|
STATE = Path(os.environ.get('S3_OUTAGE_STATE', '/tmp/s3-outage-state.json'))
|
||||||
|
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||||
|
HOST = os.environ.get('LB_HOST', 'lb')
|
||||||
|
PORT = int(os.environ.get('LB_PORT', '8080'))
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token=None, body=None, content_type=None, extra=None):
|
||||||
|
headers = dict(extra or {})
|
||||||
|
if token:
|
||||||
|
headers['Authorization'] = 'Bearer ' + token
|
||||||
|
if content_type:
|
||||||
|
headers['Content-Type'] = content_type
|
||||||
|
conn = http.client.HTTPConnection(HOST, PORT, timeout=30)
|
||||||
|
started = time.monotonic()
|
||||||
|
conn.request(method, path, body=body, headers=headers)
|
||||||
|
response = conn.getresponse()
|
||||||
|
data = response.read()
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
conn.close()
|
||||||
|
return response, data, elapsed
|
||||||
|
|
||||||
|
|
||||||
|
def show(label, response, data, elapsed):
|
||||||
|
code = ''
|
||||||
|
if response.status >= 400:
|
||||||
|
code = json.loads(data)['error']['code']
|
||||||
|
print('%-32s -> %s %-12s %5.2fs X-Instance-Id=%s' % (label, response.status, code, elapsed, 'yes' if response.getheader('X-Instance-Id') else 'no'))
|
||||||
|
|
||||||
|
|
||||||
|
def prepare():
|
||||||
|
client = Client('http://%s:%d' % (HOST, PORT))
|
||||||
|
alice = client.user('alice')
|
||||||
|
chat = client.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'outage', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||||
|
attachment, _ = client.attachment(alice, chat)
|
||||||
|
STATE.write_text(json.dumps({'token': alice['token'], 'chat': chat['id'], 'attachment': attachment['id']}))
|
||||||
|
|
||||||
|
|
||||||
|
def during():
|
||||||
|
state = json.loads(STATE.read_text())
|
||||||
|
token, chat, attachment = state['token'], state['chat'], state['attachment']
|
||||||
|
show('GET /health/live', *request('GET', '/health/live'))
|
||||||
|
show('GET /health/ready', *request('GET', '/health/ready'))
|
||||||
|
show('GET /attachments/{id}', *request('GET', '/api/v1/attachments/' + attachment, token))
|
||||||
|
show('GET /attachments/{id}/content', *request('GET', '/api/v1/attachments/' + attachment + '/content', token))
|
||||||
|
show('POST /attachments', *request('POST', '/api/v1/chats/' + chat + '/attachments?filename=down.png', token, SAMPLE, 'image/png'))
|
||||||
|
show('POST /messages (текст)', *request('POST', '/api/v1/chats/' + chat + '/messages', token, json.dumps({'text': 'пока S3 недоступен'}), 'application/json', {'Idempotency-Key': uuid.uuid4().hex}))
|
||||||
|
|
||||||
|
|
||||||
|
def after():
|
||||||
|
state = json.loads(STATE.read_text())
|
||||||
|
token, attachment = state['token'], state['attachment']
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while True:
|
||||||
|
response, data, elapsed = request('GET', '/health/ready')
|
||||||
|
if response.status == 200 or time.monotonic() > deadline:
|
||||||
|
break
|
||||||
|
time.sleep(0.5)
|
||||||
|
show('GET /health/ready', response, data, elapsed)
|
||||||
|
response, data, elapsed = request('GET', '/api/v1/attachments/' + attachment + '/content', token)
|
||||||
|
show('GET /attachments/{id}/content', response, data, elapsed)
|
||||||
|
print('sha256 совпадает:', hashlib.sha256(data).hexdigest() == hashlib.sha256(SAMPLE).hexdigest())
|
||||||
|
STATE.unlink()
|
||||||
|
|
||||||
|
|
||||||
|
{'prepare': prepare, 'during': during, 'after': after}[sys.argv[1]]()
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mode="${1:-stop}"
|
||||||
|
python3 scripts/s3-outage.py prepare
|
||||||
|
case "$mode" in
|
||||||
|
stop) docker compose stop s3 2>&1 | grep -v Container || true ;;
|
||||||
|
pause) docker compose pause s3 2>&1 | grep -v Container || true ;;
|
||||||
|
*) echo "usage: s3-outage.sh stop|pause" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
echo "## S3: $mode"
|
||||||
|
python3 scripts/s3-outage.py during
|
||||||
|
case "$mode" in
|
||||||
|
stop) docker compose start s3 2>&1 | grep -v Container || true ;;
|
||||||
|
pause) docker compose unpause s3 2>&1 | grep -v Container || true ;;
|
||||||
|
esac
|
||||||
|
echo "## S3 восстановлен"
|
||||||
|
python3 scripts/s3-outage.py after
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { S3Service } from '../storage/s3.service';
|
||||||
|
|
||||||
|
const MAX_REPORTED_KEYS = 20;
|
||||||
|
|
||||||
|
export interface ReconcileOptions {
|
||||||
|
apply: boolean;
|
||||||
|
graceMs: number;
|
||||||
|
prefix?: string;
|
||||||
|
now?: Date;
|
||||||
|
pageSize?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReconcileReport {
|
||||||
|
mode: 'apply' | 'dry-run';
|
||||||
|
grace_seconds: number;
|
||||||
|
scanned: number;
|
||||||
|
fresh_skipped: number;
|
||||||
|
referenced: number;
|
||||||
|
orphans: number;
|
||||||
|
deleted: number;
|
||||||
|
failed: number;
|
||||||
|
orphan_keys: string[];
|
||||||
|
duration_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reconcile(
|
||||||
|
prisma: Pick<PrismaClient, 'attachment'>,
|
||||||
|
s3: S3Service,
|
||||||
|
options: ReconcileOptions,
|
||||||
|
): Promise<ReconcileReport> {
|
||||||
|
const started = Date.now();
|
||||||
|
const cutoff = (options.now ?? new Date()).getTime() - options.graceMs;
|
||||||
|
const report: ReconcileReport = {
|
||||||
|
mode: options.apply ? 'apply' : 'dry-run',
|
||||||
|
grace_seconds: options.graceMs / 1000,
|
||||||
|
scanned: 0,
|
||||||
|
fresh_skipped: 0,
|
||||||
|
referenced: 0,
|
||||||
|
orphans: 0,
|
||||||
|
deleted: 0,
|
||||||
|
failed: 0,
|
||||||
|
orphan_keys: [],
|
||||||
|
duration_ms: 0,
|
||||||
|
};
|
||||||
|
let token: string | undefined;
|
||||||
|
do {
|
||||||
|
const page = await s3.listObjects(
|
||||||
|
options.prefix ?? 'attachments/',
|
||||||
|
options.pageSize ?? 500,
|
||||||
|
token,
|
||||||
|
);
|
||||||
|
token = page.nextToken;
|
||||||
|
report.scanned += page.objects.length;
|
||||||
|
const old = page.objects.filter((object) => object.lastModified.getTime() < cutoff);
|
||||||
|
report.fresh_skipped += page.objects.length - old.length;
|
||||||
|
const rows = await prisma.attachment.findMany({
|
||||||
|
where: { objectKey: { in: old.map((object) => object.key) } },
|
||||||
|
select: { objectKey: true },
|
||||||
|
});
|
||||||
|
const known = new Set(rows.map((row) => row.objectKey));
|
||||||
|
for (const { key } of old) {
|
||||||
|
if (known.has(key)) {
|
||||||
|
report.referenced++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
report.orphans++;
|
||||||
|
if (report.orphan_keys.length < MAX_REPORTED_KEYS) {
|
||||||
|
report.orphan_keys.push(key);
|
||||||
|
}
|
||||||
|
if (options.apply) {
|
||||||
|
await s3.delete(key).then(
|
||||||
|
() => report.deleted++,
|
||||||
|
() => report.failed++,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while (token);
|
||||||
|
report.duration_ms = Date.now() - started;
|
||||||
|
return report;
|
||||||
|
}
|
||||||
@@ -1,19 +1,37 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get } from '@nestjs/common';
|
||||||
import { ApiError } from '../common/filters/api-error';
|
import { ApiError } from '../common/filters/api-error';
|
||||||
import { PrismaService } from '../db/prisma.service';
|
import { PrismaService } from '../db/prisma.service';
|
||||||
|
import { S3Service } from '../storage/s3.service';
|
||||||
import { isDraining } from './shutdown';
|
import { isDraining } from './shutdown';
|
||||||
|
|
||||||
@Controller('health')
|
@Controller('health')
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly s3: S3Service,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Get('live')
|
@Get('live')
|
||||||
live(): { status: 'ok' } {
|
live(): { status: 'ok' } {
|
||||||
return { status: 'ok' };
|
return { status: 'ok' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('core')
|
||||||
|
async core(): Promise<{ status: 'ok' }> {
|
||||||
|
await this.assertCoreReady();
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
@Get('ready')
|
@Get('ready')
|
||||||
async ready(): Promise<{ status: 'ok' }> {
|
async ready(): Promise<{ status: 'ok' }> {
|
||||||
|
await this.assertCoreReady();
|
||||||
|
if (!(await this.s3.isAvailable())) {
|
||||||
|
throw new ApiError('unavailable', 'object storage unavailable');
|
||||||
|
}
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertCoreReady(): Promise<void> {
|
||||||
if (isDraining()) {
|
if (isDraining()) {
|
||||||
throw new ApiError('unavailable', 'shutting down');
|
throw new ApiError('unavailable', 'shutting down');
|
||||||
}
|
}
|
||||||
@@ -22,6 +40,5 @@ export class HealthController {
|
|||||||
} catch {
|
} catch {
|
||||||
throw new ApiError('unavailable', 'database unavailable');
|
throw new ApiError('unavailable', 'database unavailable');
|
||||||
}
|
}
|
||||||
return { status: 'ok' };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { reconcile } from './attachments/reconciler';
|
||||||
|
import { PrismaService } from './db/prisma.service';
|
||||||
|
import { S3Service } from './storage/s3.service';
|
||||||
|
|
||||||
|
const DEFAULT_GRACE_SECONDS = 3600;
|
||||||
|
const DEFAULT_INTERVAL_SECONDS = 300;
|
||||||
|
|
||||||
|
function option(name: string, fallback: number): number {
|
||||||
|
const prefix = `--${name}=`;
|
||||||
|
const raw = process.argv.find((arg) => arg.startsWith(prefix));
|
||||||
|
const value = raw ? Number(raw.slice(prefix.length)) : fallback;
|
||||||
|
if (!Number.isInteger(value) || value < 0) {
|
||||||
|
throw new Error(`--${name} must be a non-negative integer`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
process.once('SIGTERM', () => process.exit(0));
|
||||||
|
process.once('SIGINT', () => process.exit(0));
|
||||||
|
const apply = process.argv.includes('--apply');
|
||||||
|
const loop = process.argv.includes('--loop');
|
||||||
|
const graceSeconds = option('grace-seconds', DEFAULT_GRACE_SECONDS);
|
||||||
|
const intervalSeconds = option('interval-seconds', DEFAULT_INTERVAL_SECONDS);
|
||||||
|
const prisma = new PrismaService();
|
||||||
|
const s3 = new S3Service();
|
||||||
|
do {
|
||||||
|
try {
|
||||||
|
const report = await reconcile(prisma, s3, {
|
||||||
|
apply,
|
||||||
|
graceMs: graceSeconds * 1000,
|
||||||
|
});
|
||||||
|
process.stdout.write(`${JSON.stringify(report)}\n`);
|
||||||
|
} catch (error) {
|
||||||
|
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||||
|
Logger.error(`reconcile pass aborted: ${reason}`, 'Reconciler');
|
||||||
|
process.exitCode = loop ? 0 : 1;
|
||||||
|
}
|
||||||
|
if (loop) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000));
|
||||||
|
}
|
||||||
|
} while (loop);
|
||||||
|
await prisma.$disconnect();
|
||||||
|
s3.onModuleDestroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
Logger.error(error instanceof Error ? error.message : 'fatal error', 'Reconciler');
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import {
|
import {
|
||||||
DeleteObjectCommand,
|
DeleteObjectCommand,
|
||||||
GetObjectCommand,
|
GetObjectCommand,
|
||||||
|
HeadBucketCommand,
|
||||||
|
ListObjectsV2Command,
|
||||||
PutObjectCommand,
|
PutObjectCommand,
|
||||||
S3Client,
|
S3Client,
|
||||||
} from '@aws-sdk/client-s3';
|
} from '@aws-sdk/client-s3';
|
||||||
@@ -12,6 +14,12 @@ import { ApiError } from '../common/filters/api-error';
|
|||||||
const CONNECT_TIMEOUT_MS = 1000;
|
const CONNECT_TIMEOUT_MS = 1000;
|
||||||
const IDLE_TIMEOUT_MS = 5000;
|
const IDLE_TIMEOUT_MS = 5000;
|
||||||
const OPERATION_TIMEOUT_MS = 20000;
|
const OPERATION_TIMEOUT_MS = 20000;
|
||||||
|
const HEALTH_TIMEOUT_MS = 1000;
|
||||||
|
|
||||||
|
export interface ObjectPage {
|
||||||
|
objects: { key: string; lastModified: Date }[];
|
||||||
|
nextToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface StoredFile {
|
export interface StoredFile {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -89,6 +97,42 @@ export class S3Service implements OnModuleDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async isAvailable(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }), {
|
||||||
|
abortSignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async listObjects(
|
||||||
|
prefix: string,
|
||||||
|
pageSize: number,
|
||||||
|
token?: string,
|
||||||
|
): Promise<ObjectPage> {
|
||||||
|
const page = await this.guard(`list ${prefix}`, () =>
|
||||||
|
this.client.send(
|
||||||
|
new ListObjectsV2Command({
|
||||||
|
Bucket: this.bucket,
|
||||||
|
Prefix: prefix,
|
||||||
|
MaxKeys: pageSize,
|
||||||
|
ContinuationToken: token,
|
||||||
|
}),
|
||||||
|
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
objects: (page.Contents ?? []).map((object) => ({
|
||||||
|
key: object.Key!,
|
||||||
|
lastModified: object.LastModified!,
|
||||||
|
})),
|
||||||
|
nextToken: page.NextContinuationToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async delete(key: string): Promise<void> {
|
async delete(key: string): Promise<void> {
|
||||||
await this.guard(`delete ${key}`, () =>
|
await this.guard(`delete ${key}`, () =>
|
||||||
this.client.send(
|
this.client.send(
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { createHash, randomUUID } from 'crypto';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { reconcile } from '../src/attachments/reconciler';
|
||||||
|
import { PrismaService } from '../src/db/prisma.service';
|
||||||
|
import { S3Service } from '../src/storage/s3.service';
|
||||||
|
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
||||||
|
import { SAMPLE_PNG } from './images';
|
||||||
|
|
||||||
|
const HOUR_MS = 60 * 60 * 1000;
|
||||||
|
|
||||||
|
describe('Сверка объектов S3 с метаданными (e2e)', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let server: any;
|
||||||
|
let prisma: PrismaService;
|
||||||
|
let s3: S3Service;
|
||||||
|
let alice: TestUser;
|
||||||
|
let chatId: string;
|
||||||
|
let dir: string;
|
||||||
|
|
||||||
|
const putObject = async (key: string): Promise<void> => {
|
||||||
|
const path = join(dir, randomUUID());
|
||||||
|
writeFileSync(path, SAMPLE_PNG);
|
||||||
|
await s3.putFile({
|
||||||
|
key,
|
||||||
|
path,
|
||||||
|
size: SAMPLE_PNG.length,
|
||||||
|
contentType: 'image/png',
|
||||||
|
sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const exists = async (key: string): Promise<boolean> => {
|
||||||
|
const page = await s3.listObjects(key, 1);
|
||||||
|
return page.objects.some((object) => object.key === key);
|
||||||
|
};
|
||||||
|
|
||||||
|
const scope = () => `reconcile-test/${randomUUID()}/`;
|
||||||
|
const later = () => new Date(Date.now() + 2 * HOUR_MS);
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
({ app, server } = await createTestApp());
|
||||||
|
prisma = app.get(PrismaService);
|
||||||
|
s3 = app.get(S3Service);
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'reconcile-test-'));
|
||||||
|
alice = await registerUser(server, 'rec_alice');
|
||||||
|
const chat = await request(server)
|
||||||
|
.post('/api/v1/chats')
|
||||||
|
.set('Authorization', bearer(alice))
|
||||||
|
.send({ title: 'Reconcile', member_ids: [alice.id] })
|
||||||
|
.expect(201);
|
||||||
|
chatId = chat.body.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
const key = `${prefix}orphan`;
|
||||||
|
await putObject(key);
|
||||||
|
const options = { graceMs: HOUR_MS, prefix, now: later() };
|
||||||
|
|
||||||
|
const dry = await reconcile(prisma, s3, { ...options, apply: false });
|
||||||
|
expect(dry).toMatchObject({ mode: 'dry-run', scanned: 1, orphans: 1, deleted: 0, orphan_keys: [key] });
|
||||||
|
expect(await exists(key)).toBe(true);
|
||||||
|
|
||||||
|
const applied = await reconcile(prisma, s3, { ...options, apply: true });
|
||||||
|
expect(applied).toMatchObject({ mode: 'apply', orphans: 1, deleted: 1, failed: 0 });
|
||||||
|
expect(await exists(key)).toBe(false);
|
||||||
|
|
||||||
|
const again = await reconcile(prisma, s3, { ...options, apply: true });
|
||||||
|
expect(again).toMatchObject({ scanned: 0, orphans: 0, deleted: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('не трогает свежий объект внутри grace period', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
const key = `${prefix}fresh`;
|
||||||
|
await putObject(key);
|
||||||
|
const report = await reconcile(prisma, s3, { apply: true, graceMs: HOUR_MS, prefix });
|
||||||
|
expect(report).toMatchObject({ scanned: 1, fresh_skipped: 1, orphans: 0, deleted: 0 });
|
||||||
|
expect(await exists(key)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('не трогает старый объект, на который есть метаданные', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
const key = `${prefix}referenced`;
|
||||||
|
await putObject(key);
|
||||||
|
await prisma.attachment.create({
|
||||||
|
data: {
|
||||||
|
chatId,
|
||||||
|
ownerId: alice.id,
|
||||||
|
filename: 'a.png',
|
||||||
|
contentType: 'image/png',
|
||||||
|
sizeBytes: SAMPLE_PNG.length,
|
||||||
|
sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'),
|
||||||
|
objectKey: key,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const report = await reconcile(prisma, s3, {
|
||||||
|
apply: true,
|
||||||
|
graceMs: HOUR_MS,
|
||||||
|
prefix,
|
||||||
|
now: later(),
|
||||||
|
});
|
||||||
|
expect(report).toMatchObject({ scanned: 1, referenced: 1, orphans: 0, deleted: 0 });
|
||||||
|
expect(await exists(key)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('при отказе PostgreSQL проход прерывается и ничего не удаляет', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
const key = `${prefix}orphan`;
|
||||||
|
await putObject(key);
|
||||||
|
const broken = {
|
||||||
|
attachment: {
|
||||||
|
findMany: jest.fn().mockRejectedValue(new Error('database down')),
|
||||||
|
},
|
||||||
|
} as unknown as PrismaService;
|
||||||
|
await expect(
|
||||||
|
reconcile(broken, s3, { apply: true, graceMs: HOUR_MS, prefix, now: later() }),
|
||||||
|
).rejects.toThrow('database down');
|
||||||
|
expect(await exists(key)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('сбой удаления считается и повторяется на следующем проходе', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
const key = `${prefix}orphan`;
|
||||||
|
await putObject(key);
|
||||||
|
const options = { apply: true, graceMs: HOUR_MS, prefix, now: later() };
|
||||||
|
const remove = jest.spyOn(s3, 'delete').mockRejectedValueOnce(new Error('s3 down'));
|
||||||
|
try {
|
||||||
|
const failed = await reconcile(prisma, s3, options);
|
||||||
|
expect(failed).toMatchObject({ orphans: 1, deleted: 0, failed: 1 });
|
||||||
|
expect(await exists(key)).toBe(true);
|
||||||
|
} finally {
|
||||||
|
remove.mockRestore();
|
||||||
|
}
|
||||||
|
const retried = await reconcile(prisma, s3, options);
|
||||||
|
expect(retried).toMatchObject({ orphans: 1, deleted: 1, failed: 0 });
|
||||||
|
expect(await exists(key)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('обходит все страницы листинга', async () => {
|
||||||
|
const prefix = scope();
|
||||||
|
await Promise.all([1, 2, 3].map((n) => putObject(`${prefix}${n}`)));
|
||||||
|
const report = await reconcile(prisma, s3, {
|
||||||
|
apply: true,
|
||||||
|
graceMs: HOUR_MS,
|
||||||
|
prefix,
|
||||||
|
now: later(),
|
||||||
|
pageSize: 1,
|
||||||
|
});
|
||||||
|
expect(report).toMatchObject({ scanned: 3, orphans: 3, deleted: 3 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('реальная загрузка остаётся доступной после сверки всего bucket префикса вложений', async () => {
|
||||||
|
const upload = await request(server)
|
||||||
|
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
|
||||||
|
.set('Authorization', bearer(alice))
|
||||||
|
.set('Content-Type', 'image/png')
|
||||||
|
.send(SAMPLE_PNG)
|
||||||
|
.expect(201);
|
||||||
|
const report = await reconcile(prisma, s3, { apply: true, graceMs: HOUR_MS });
|
||||||
|
expect(report.fresh_skipped).toBeGreaterThanOrEqual(1);
|
||||||
|
await request(server)
|
||||||
|
.get(`/api/v1/attachments/${upload.body.id}/content`)
|
||||||
|
.set('Authorization', bearer(alice))
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Готовность при отказе S3 (e2e)', () => {
|
||||||
|
it('ready — 503 с заголовками за короткое время, live и core — 200', async () => {
|
||||||
|
const { app, server } = await createTestApp({ S3_ENDPOINT: 'http://127.0.0.1:9' });
|
||||||
|
try {
|
||||||
|
const started = Date.now();
|
||||||
|
const res = await request(server).get('/health/ready').expect(503);
|
||||||
|
expect(Date.now() - started).toBeLessThan(2000);
|
||||||
|
expect(res.body.error.code).toBe('unavailable');
|
||||||
|
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
|
||||||
|
expect(res.headers['x-instance-id']).toBeTruthy();
|
||||||
|
await request(server).get('/health/live').expect(200);
|
||||||
|
await request(server).get('/health/core').expect(200);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('при рабочем S3 ready — 200', async () => {
|
||||||
|
const { app, server } = await createTestApp();
|
||||||
|
try {
|
||||||
|
await request(server).get('/health/ready').expect(200);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user