Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.

Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready;
компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
Mlvn
2026-11-12 18:08:47 +03:00
parent ec540a1a72
commit 7cbb75c897
43 changed files with 6075 additions and 36 deletions
+146
View File
@@ -0,0 +1,146 @@
#!/bin/sh
# Трек 5: внедрить orphan + missing, показать dry-run и apply, доказать защиту fresh.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
cd "$ROOT"
OUT=${OUT:-evidence/reconcile.txt}
mkdir -p evidence
: >"$OUT"
log() { echo "$@" | tee -a "$OUT"; }
BUCKET=$(grep -E '^S3_BUCKET=' .env | cut -d= -f2-)
BUCKET=${BUCKET:-messenger-attachments}
ROOT_USER=$(grep -E '^MINIO_ROOT_USER=' .env | cut -d= -f2-)
ROOT_PASS=$(grep -E '^MINIO_ROOT_PASSWORD=' .env | cut -d= -f2-)
ROOT_USER=${ROOT_USER:-minioadmin}
ROOT_PASS=${ROOT_PASS:-minioadmin-secret}
ORPHAN_KEY="originals/00000000-0000-4000-8000-0000000000aa"
log "=== seed orphan object via root PutObject (python/minio not required: curl+aws style via go) ==="
# Используем временный контейнер с нашим s3bootstrap-окружением нельзя для PUT.
# Кладём объект через API MinIO SDK в одноразовом python boto? Проще — docker run с
# нашим образом и маленьким go-one-liner... Пишем через awscli-совместимый путь:
# minio client отсутствует → используем python3 + urllib подписанный запрос слишком сложен.
# Простой путь: временный Go в scripts/seed_orphan — нет. Используем docker compose run
# с entrypoint /s3bootstrap нельзя. Добавим флаг...
# Практика: python boto3 если есть, иначе raw Put через minio-go в compose run server?
# Самое простое — python3 и hashlib hmac для SigV4.
python3 - <<PY | tee -a "$OUT"
import hashlib, hmac, datetime, urllib.request
access="${ROOT_USER}"
secret="${ROOT_PASS}"
bucket="${BUCKET}"
key="${ORPHAN_KEY}"
host="127.0.0.1:9000"
body=b"orphan-bytes"
t=datetime.datetime.utcnow()
amz=t.strftime("%Y%m%dT%H%M%SZ")
datestamp=t.strftime("%Y%m%d")
payload_hash=hashlib.sha256(body).hexdigest()
canonical_headers=f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz}\n"
signed_headers="host;x-amz-content-sha256;x-amz-date"
canonical_request="\n".join([
"PUT", f"/{bucket}/{key}", "", canonical_headers, signed_headers, payload_hash
])
credential_scope=f"{datestamp}/us-east-1/s3/aws4_request"
string_to_sign="\n".join([
"AWS4-HMAC-SHA256", amz, credential_scope, hashlib.sha256(canonical_request.encode()).hexdigest()
])
def sign(key, msg):
return hmac.new(key, msg.encode(), hashlib.sha256).digest()
kDate=sign(("AWS4"+secret).encode(), datestamp)
kRegion=sign(kDate, "us-east-1")
kService=sign(kRegion, "s3")
kSigning=sign(kService, "aws4_request")
signature=hmac.new(kSigning, string_to_sign.encode(), hashlib.sha256).hexdigest()
auth=f"AWS4-HMAC-SHA256 Credential={access}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
req=urllib.request.Request(
f"http://{host}/{bucket}/{key}", data=body, method="PUT",
headers={
"Host": host,
"x-amz-content-sha256": payload_hash,
"x-amz-date": amz,
"Authorization": auth,
"Content-Length": str(len(body)),
},
)
try:
with urllib.request.urlopen(req) as resp:
print("orphan_put", resp.status)
except Exception as e:
print("orphan_put_err", e)
raise
PY
log "=== seed missing metadata (DB row, no S3 object) ==="
docker compose --env-file .env exec -T postgres \
psql -U messenger -d messenger -v ON_ERROR_STOP=1 <<'SQL' | tee -a "$OUT"
DO $$
DECLARE
uid uuid;
cid uuid;
aid uuid := '11111111-1111-4111-8111-111111111111';
BEGIN
SELECT id INTO uid FROM users LIMIT 1;
IF uid IS NULL THEN
RAISE NOTICE 'no users yet — skip missing seed';
RETURN;
END IF;
SELECT c.id INTO cid
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = uid
LIMIT 1;
IF cid IS NULL THEN
RAISE NOTICE 'no chat — skip missing seed';
RETURN;
END IF;
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, status, error_code, created_at, updated_at
) VALUES (
aid, cid, uid, 'missing.png', 'image/png', 12,
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'originals/11111111-1111-4111-8111-111111111111',
'ready', NULL,
now() - interval '2 hours', now() - interval '2 hours'
) ON CONFLICT (id) DO UPDATE SET created_at = EXCLUDED.created_at, updated_at = EXCLUDED.updated_at;
END $$;
SQL
log "=== dry-run grace=0 ==="
docker compose --env-file .env run --rm --no-deps reconcile -grace-seconds=0 2>&1 | tee -a "$OUT"
log "=== apply grace=0 ==="
docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT"
log "=== second apply (idempotent) ==="
docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT"
log "=== fresh orphan skipped with default grace ==="
python3 - <<PY | tee -a "$OUT"
import hashlib, hmac, datetime, urllib.request
access="${ROOT_USER}"; secret="${ROOT_PASS}"; bucket="${BUCKET}"
key="originals/00000000-0000-4000-8000-0000000000bb"
host="127.0.0.1:9000"; body=b"fresh"
t=datetime.datetime.utcnow(); amz=t.strftime("%Y%m%dT%H%M%SZ"); datestamp=t.strftime("%Y%m%d")
payload_hash=hashlib.sha256(body).hexdigest()
canonical_headers=f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz}\n"
signed_headers="host;x-amz-content-sha256;x-amz-date"
canonical_request="\n".join(["PUT", f"/{bucket}/{key}", "", canonical_headers, signed_headers, payload_hash])
credential_scope=f"{datestamp}/us-east-1/s3/aws4_request"
string_to_sign="\n".join(["AWS4-HMAC-SHA256", amz, credential_scope, hashlib.sha256(canonical_request.encode()).hexdigest()])
def sign(key, msg): return hmac.new(key, msg.encode(), hashlib.sha256).digest()
kSigning=sign(sign(sign(sign(("AWS4"+secret).encode(), datestamp), "us-east-1"), "s3"), "aws4_request")
signature=hmac.new(kSigning, string_to_sign.encode(), hashlib.sha256).hexdigest()
auth=f"AWS4-HMAC-SHA256 Credential={access}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
req=urllib.request.Request(f"http://{host}/{bucket}/{key}", data=body, method="PUT", headers={
"Host": host, "x-amz-content-sha256": payload_hash, "x-amz-date": amz, "Authorization": auth,
"Content-Length": str(len(body)),
})
with urllib.request.urlopen(req) as resp:
print("fresh_put", resp.status)
PY
docker compose --env-file .env run --rm --no-deps reconcile 2>&1 | tee -a "$OUT"
log "wrote $OUT"