This commit is contained in:
2026-10-30 21:09:56 +03:00
parent ec540a1a72
commit 3223dd469a
87 changed files with 15475 additions and 33 deletions
+154
View File
@@ -0,0 +1,154 @@
#!/bin/sh
# Track 1 experiment: API RSS during transfer + approx body bytes through API.
# Direct PUT: client→MinIO (compose net). Complete measured separately.
#
# ./tools/exp_direct_vs_proxy.sh
# Optional: SIZES_MB="1 4" CONCURRENCY=3
set -eu
ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
. "$ROOT/student-tests/lib.sh"
COMPOSE="docker compose --env-file $ROOT/.env -f $ROOT/compose.yaml"
SIZES_MB="${SIZES_MB:-1 4}"
CONCURRENCY="${CONCURRENCY:-3}"
OUT_DIR="${OUT_DIR:-$ROOT/artifacts/track1}"
mkdir -p "$OUT_DIR"
need docker
rss_sum() {
ids=$($COMPOSE ps -q api)
total=0
for id in $ids; do
[ -n "$id" ] || continue
rss=$(docker exec "$id" sh -c "awk '/^VmRSS:/ {print \$2}' /proc/1/status" 2>/dev/null || echo 0)
total=$((total + rss))
done
printf '%s' "$total"
}
sample_peak() {
dur=${1:-3}
peak=$(rss_sum)
end=$(( $(date +%s) + dur ))
while [ "$(date +%s)" -lt "$end" ]; do
cur=$(rss_sum)
[ "$cur" -gt "$peak" ] && peak=$cur
sleep 0.15
done
printf '%s' "$peak"
}
make_png() {
mb=$1
out=$2
python3 - "$mb" "$out" <<'PY'
import struct, zlib, sys
mb = float(sys.argv[1])
path = sys.argv[2]
target = int(mb * 1024 * 1024)
w, h = 320, 200
raw = b"".join(b"\x00" + bytes(w * 3) for _ in range(h))
def chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff)
ihdr = chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
idat = chunk(b"IDAT", zlib.compress(raw, 9))
sig = b"\x89PNG\r\n\x1a\n"
base = sig + ihdr + idat + chunk(b"IEND", b"")
pad_need = max(0, target - len(base) - 12)
text = b"Comment\0" + (b"x" * pad_need)
open(path, "wb").write(sig + ihdr + idat + chunk(b"tEXt", text) + chunk(b"IEND", b""))
PY
}
put_direct() {
url=$1
ct=$2
file=$3
$COMPOSE run --rm --no-deps \
-v "$file:/tmp/up.bin:ro" \
--entrypoint curl api \
-sS -m 120 -o /dev/null \
-X PUT -H "Content-Type: $ct" --data-binary @/tmp/up.bin \
"$url" >/dev/null
}
register_user exp_alice3
ALICE_TOKEN=$TOKEN
ALICE_ID=$USER_ID
create_chat "exp-track1c" "[\"$ALICE_ID\"]"
RESULT="$OUT_DIR/results.tsv"
printf 'mode\tphase\tsize_mb\trss_before_kb\trss_peak_kb\trss_delta_kb\tapi_body_bytes_approx\n' > "$RESULT"
for mb in $SIZES_MB; do
f="$OUT_DIR/payload_${mb}mb.png"
make_png "$mb" "$f"
sha=$(sha256_file "$f")
sz=$(wc -c < "$f" | tr -d ' ')
api_bytes=$((CONCURRENCY * sz))
# --- proxy transfer ---
sleep 1
before=$(rss_sum)
i=0
pids=""
while [ "$i" -lt "$CONCURRENCY" ]; do
( upload_file "$CHAT_ID" "$f" "p_${mb}_$i.png" "image/png" >/dev/null 2>&1 || true ) &
pids="$pids $!"
i=$((i + 1))
done
peak=$(sample_peak 10)
for p in $pids; do wait "$p" || true; done
[ "$peak" -lt "$before" ] && peak=$before
delta=$((peak - before))
printf 'proxy\ttransfer\t%s\t%s\t%s\t%s\t%s\n' "$mb" "$before" "$peak" "$delta" "$api_bytes" | tee -a "$RESULT"
# --- direct: create sessions, then PUT-only window ---
sess="$OUT_DIR/sess_${mb}.tsv"
: > "$sess"
i=0
while [ "$i" -lt "$CONCURRENCY" ]; do
http_json POST "/api/v1/chats/$CHAT_ID/direct-uploads" \
-H "Authorization: Bearer $ALICE_TOKEN" \
-H 'Content-Type: application/json' \
-d "{\"filename\":\"d_${mb}_$i.png\",\"content_type\":\"image/png\",\"size_bytes\":$sz,\"sha256\":\"$sha\"}"
[ "$HTTP_CODE" = "201" ] || die "init failed: $HTTP_BODY"
printf '%s\t%s\t%s\n' \
"$(printf '%s' "$HTTP_BODY" | jq -r .id)" \
"$(printf '%s' "$HTTP_BODY" | jq -r .upload_url)" \
"$(printf '%s' "$HTTP_BODY" | jq -r '.headers["Content-Type"]')" >> "$sess"
i=$((i + 1))
done
sleep 1
before=$(rss_sum)
pids=""
while IFS="$(printf '\t')" read -r uid url ct; do
[ -n "$url" ] || continue
( put_direct "$url" "$ct" "$f" ) &
pids="$pids $!"
done < "$sess"
peak=$(sample_peak 15)
for p in $pids; do wait "$p" || true; done
[ "$peak" -lt "$before" ] && peak=$before
delta=$((peak - before))
printf 'direct\ttransfer\t%s\t%s\t%s\t%s\t%s\n' "$mb" "$before" "$peak" "$delta" "0" | tee -a "$RESULT"
# --- direct complete ---
before=$(rss_sum)
while IFS="$(printf '\t')" read -r uid url ct; do
[ -n "$uid" ] || continue
http_json POST "/api/v1/direct-uploads/$uid/complete" \
-H "Authorization: Bearer $ALICE_TOKEN"
[ "$HTTP_CODE" = "201" ] || die "complete failed id=$uid body=$HTTP_BODY"
done < "$sess"
peak=$(rss_sum)
[ "$peak" -lt "$before" ] && peak=$before
delta=$((peak - before))
printf 'direct\tcomplete\t%s\t%s\t%s\t%s\t%s\n' "$mb" "$before" "$peak" "$delta" "$api_bytes" | tee -a "$RESULT"
done
echo "wrote $RESULT"
cat "$RESULT"
Binary file not shown.

After

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 B

+61
View File
@@ -0,0 +1,61 @@
#!/bin/sh
# Expire pending direct-upload sessions past expires_at and delete their S3
# objects (if any). Dry-run by default.
#
# ./tools/gc_direct_uploads.sh
# APPLY=1 ./tools/gc_direct_uploads.sh
set -eu
ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
COMPOSE="docker compose --env-file $ROOT/.env -f $ROOT/compose.yaml"
APPLY="${APPLY:-0}"
S3_BUCKET=$($COMPOSE exec -T api sh -c 'printf %s "$S3_BUCKET"')
[ -n "$S3_BUCKET" ] || { echo "S3_BUCKET empty" >&2; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
echo "gc_direct_uploads: apply=$APPLY"
$COMPOSE exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "
SELECT id || E'\''\t'\'' || s3_key FROM direct_uploads
WHERE status = '\''pending'\'' AND expires_at < now()
"' > "$TMP/stale.tsv" || true
n=$(wc -l < "$TMP/stale.tsv" | tr -d ' ')
echo "gc_direct_uploads: stale_pending=$n"
if [ ! -s "$TMP/stale.tsv" ]; then
echo "gc_direct_uploads: nothing to do"
exit 0
fi
while IFS="$(printf '\t')" read -r id key; do
[ -n "$id" ] || continue
echo " STALE id=$id key=$key"
done < "$TMP/stale.tsv"
if [ "$APPLY" != "1" ]; then
echo "gc_direct_uploads: dry-run; set APPLY=1 to expire + delete objects"
exit 0
fi
$COMPOSE exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "
UPDATE direct_uploads SET status = '\''expired'\'', updated_at = now()
WHERE status = '\''pending'\'' AND expires_at < now()
"' >/dev/null
cut -f2 "$TMP/stale.tsv" | $COMPOSE run --rm --no-deps --entrypoint /bin/sh minio-init -c "
set -eu
mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
while IFS= read -r key; do
[ -n \"\$key\" ] || continue
mc rm --force \"local/\$S3_BUCKET/\$key\" 2>/dev/null || true
echo \"deleted \$key\"
done
"
echo "gc_direct_uploads: done"
+111
View File
@@ -0,0 +1,111 @@
#!/bin/sh
# Reconcile S3 orphans: bucket objects with no matching attachments.s3_key in PG.
#
# Upload path compensation: S3 PUT → PG INSERT; on INSERT failure the API
# best-effort DeleteObject. This script cleans leftovers after crashes between
# PUT and compensate (or a failed DeleteObject).
#
# Dry-run by default. Fresh objects inside GRACE_SECONDS are never deleted.
#
# ./tools/gc_orphans.sh
# APPLY=1 GRACE_SECONDS=3600 ./tools/gc_orphans.sh
set -eu
ROOT="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
COMPOSE="docker compose --env-file $ROOT/.env -f $ROOT/compose.yaml"
GRACE_SECONDS="${GRACE_SECONDS:-3600}"
APPLY="${APPLY:-0}"
PREFIX="${ORPHAN_PREFIX:-attachments/}"
S3_BUCKET=$($COMPOSE exec -T api sh -c 'printf %s "$S3_BUCKET"')
[ -n "$S3_BUCKET" ] || { echo "S3_BUCKET empty" >&2; exit 1; }
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
echo "gc_orphans: bucket=$S3_BUCKET grace=${GRACE_SECONDS}s apply=$APPLY prefix=$PREFIX"
$COMPOSE run --rm --no-deps --entrypoint /bin/sh minio-init -c "
set -eu
mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
mc ls --recursive --json \"local/\$S3_BUCKET/$PREFIX\" || true
" > "$TMP/s3.json"
# Known keys: ready attachments + still-pending direct uploads (Track 1).
$COMPOSE exec -T db sh -c \
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "
SELECT s3_key FROM attachments
UNION
SELECT s3_key FROM direct_uploads WHERE status = '\''pending'\''
"' \
> "$TMP/pg.keys"
python3 - "$TMP/s3.json" "$TMP/pg.keys" "$GRACE_SECONDS" "$TMP/del.keys" <<'PY'
import json, sys, time
from datetime import datetime
s3_path, pg_path, grace_s, out_path = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
now = time.time()
known = {line.strip() for line in open(pg_path) if line.strip()}
orphans = []
for line in open(s3_path):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
key = obj.get("key") or obj.get("Key")
if not key:
continue
# mc ls under prefix returns keys relative to that prefix.
if not key.startswith("attachments/"):
key = "attachments/" + key.lstrip("/")
if key in known:
continue
age = None
lm = obj.get("lastModified") or obj.get("last_modified")
if lm:
try:
age = now - datetime.fromisoformat(lm.replace("Z", "+00:00")).timestamp()
except Exception:
age = None
orphans.append((key, age, obj.get("size")))
print(f"gc_orphans: scanned orphans={len(orphans)} known_pg={len(known)}")
to_delete = []
for key, age, size in orphans:
age_s = f"{int(age)}s" if age is not None else "?"
if age is not None and age < grace_s:
print(f" SKIP (grace) key={key} age={age_s} size={size}")
continue
print(f" ORPHAN key={key} age={age_s} size={size}")
to_delete.append(key)
with open(out_path, "w") as f:
f.write("\n".join(to_delete) + ("\n" if to_delete else ""))
print(f"gc_orphans: candidates={len(to_delete)}")
PY
if [ "$APPLY" != "1" ]; then
echo "gc_orphans: dry-run; set APPLY=1 to delete candidates older than grace."
exit 0
fi
if [ ! -s "$TMP/del.keys" ]; then
echo "gc_orphans: nothing to delete"
exit 0
fi
$COMPOSE run --rm --no-deps --entrypoint /bin/sh minio-init -c "
set -eu
mc alias set local \"\$S3_ENDPOINT\" \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null
while IFS= read -r key; do
[ -n \"\$key\" ] || continue
echo \"deleting \$S3_BUCKET/\$key\"
mc rm --force \"local/\$S3_BUCKET/\$key\"
done
" < "$TMP/del.keys"
echo "gc_orphans: delete done"
+111
View File
@@ -0,0 +1,111 @@
// Step 5 smoke: PNG / JPEG / truncated PNG / non-image / size limit.
#include "image_util.hpp"
#include <cstdint>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#ifndef IMAGE_SMOKE_FIXTURES
#define IMAGE_SMOKE_FIXTURES "tools/fixtures"
#endif
namespace {
std::vector<std::uint8_t> read_all(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in) {
throw std::runtime_error("cannot open " + path);
}
return std::vector<std::uint8_t>((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
}
bool expect_ok(const char* name, const std::vector<std::uint8_t>& bytes,
const char* want_ct) {
ImageLimits lim;
ImageInfo info;
auto rej = validate_image(bytes.data(), bytes.size(), lim, info);
if (rej) {
std::cerr << name << ": expected OK, got " << image_reject_code(*rej)
<< "\n";
return false;
}
if (info.content_type != want_ct) {
std::cerr << name << ": content_type " << info.content_type << "\n";
return false;
}
std::cout << name << ": OK " << info.content_type << " " << info.width
<< "x" << info.height << "\n";
return true;
}
bool expect_reject(const char* name, const std::vector<std::uint8_t>& bytes,
ImageReject want) {
ImageLimits lim;
ImageInfo info;
auto rej = validate_image(bytes.data(), bytes.size(), lim, info);
if (!rej || *rej != want) {
std::cerr << name << ": expected " << image_reject_code(want) << ", got "
<< (rej ? image_reject_code(*rej) : "OK") << "\n";
return false;
}
std::cout << name << ": OK reject=" << image_reject_code(want) << "\n";
return true;
}
} // namespace
int main(int argc, char** argv) {
try {
const std::string dir =
(argc > 1) ? argv[1] : std::string(IMAGE_SMOKE_FIXTURES);
const auto png = read_all(dir + "/tiny.png");
const auto jpg = read_all(dir + "/tiny.jpg");
bool ok = true;
ok &= expect_ok("png", png, "image/png");
ok &= expect_ok("jpeg", jpg, "image/jpeg");
std::vector<std::uint8_t> trunc(png.begin(),
png.begin() + std::min<std::size_t>(16, png.size()));
ok &= expect_reject("truncated_png", trunc, ImageReject::invalid_image);
std::vector<std::uint8_t> spoof = jpg;
spoof[0] = 'G';
spoof[1] = 'I';
spoof[2] = 'F';
ok &= expect_reject("not_image", spoof, ImageReject::unsupported_media_type);
ImageLimits tiny_lim;
tiny_lim.max_bytes = 10;
ImageInfo info;
auto rej = validate_image(png.data(), png.size(), tiny_lim, info);
if (!rej || *rej != ImageReject::payload_too_large) {
std::cerr << "max_bytes: FAIL\n";
ok = false;
} else {
std::cout << "max_bytes: OK\n";
}
// JPEG bytes sniffed as jpeg regardless of any HTTP Content-Type.
auto sniffed = sniff_content_type(jpg.data(), jpg.size());
if (!sniffed || *sniffed != "image/jpeg") {
std::cerr << "sniff_jpeg: FAIL\n";
ok = false;
} else {
std::cout << "sniff_jpeg: OK (MIME spoof would be ignored)\n";
}
if (!ok) {
return 1;
}
std::cout << "image_smoke: OK\n";
return 0;
} catch (const std::exception& e) {
std::cerr << "image_smoke: FAIL: " << e.what() << "\n";
return 1;
}
}
+35
View File
@@ -0,0 +1,35 @@
// Small smoke tool for step 4: put → get → delete against MinIO.
#include "s3_client.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
int main() {
try {
auto cfg = S3Client::from_env();
S3Client s3(cfg);
const std::string key = "smoke/step4.txt";
const std::string payload = "lab4-s3-smoke-ok";
std::istringstream in(payload);
s3.put_object(key, in, static_cast<std::int64_t>(payload.size()),
"text/plain");
std::ostringstream out;
s3.get_object(key, out);
if (out.str() != payload) {
std::cerr << "mismatch: got [" << out.str() << "]\n";
return 2;
}
s3.delete_object(key);
std::cout << "s3_smoke: OK bucket=" << cfg.bucket << " key=" << key << "\n";
return 0;
} catch (const std::exception& e) {
std::cerr << "s3_smoke: FAIL: " << e.what() << "\n";
return 1;
}
}