forked from mtusi2026/mtusi2026lab4
feat: add 4 grade things
This commit is contained in:
@@ -1,23 +1,37 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
# Configuration
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
COMPOSE = docker compose --project-name highload-lab4 --env-file .env -f compose.yml
|
||||
CLEANUP_ARGS ?= --dry-run
|
||||
|
||||
COMPOSE = docker compose --project-name highload-lab4 --env-file .env -f compose.yml
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-grade3 test-grade3-failures
|
||||
.PHONY: app-init app-build app-up app-start app-stop app-down app-restart app-logs app-status test-backend test-baseline test-baseline-persistence
|
||||
.PHONY: \
|
||||
help \
|
||||
app-init app-build app-up app-start app-stop app-down app-restart app-logs app-status \
|
||||
attachments-cleanup \
|
||||
check validate test load test-persistence test-failover \
|
||||
test-backend test-baseline test-baseline-persistence test-grade3 test-grade3-failures \
|
||||
test-attachment-validation test-attachment-access test-upload-recovery test-attachment-cleanup test-s3-permissions test-upload-memory
|
||||
|
||||
|
||||
|
||||
help:
|
||||
@echo "app-build: build application images; app-up: build and start the full stack"
|
||||
@echo "app-start: start without rebuilding; app-stop: stop and keep containers"
|
||||
@echo "app-down: remove containers and networks, keeping data volumes"
|
||||
@echo "app-restart: restart the stack; app-logs / app-status: inspect services"
|
||||
@echo "test-attachment-validation / test-attachment-access / test-upload-recovery / test-attachment-cleanup / test-s3-permissions"
|
||||
@echo "test-upload-memory: 10-client memory experiment; attachments-cleanup: dry run (CLEANUP_ARGS= to apply)"
|
||||
@echo "test-grade3 / test-grade3-failures: attachment checks; second target temporarily stops this stack services"
|
||||
@echo "test-backend: Go race tests; test-baseline: transferred API checks"
|
||||
@echo "test-baseline-persistence: transferred API checks across a restart"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
|
||||
|
||||
|
||||
app-init:
|
||||
$(PYTHON) scripts/init_env.py
|
||||
chmod +x scripts/restart.sh scripts/stop-one.sh
|
||||
@@ -46,20 +60,12 @@ app-logs:
|
||||
app-status:
|
||||
$(COMPOSE) ps --all
|
||||
|
||||
test-backend: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests
|
||||
|
||||
test-baseline:
|
||||
$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-baseline-persistence:
|
||||
$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)" --restart
|
||||
attachments-cleanup:
|
||||
$(COMPOSE) run --rm --no-deps upload-cleanup ./messenger attachments-cleanup $(CLEANUP_ARGS)
|
||||
|
||||
test-grade3:
|
||||
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-grade3-failures:
|
||||
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)" --failures
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -80,3 +86,41 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
|
||||
|
||||
test-backend: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests
|
||||
|
||||
test-baseline:
|
||||
$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-baseline-persistence:
|
||||
$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)" --restart
|
||||
|
||||
test-grade3:
|
||||
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-grade3-failures:
|
||||
$(PYTHON) scripts/check_grade3.py --base-url "$(BASE_URL)" --failures
|
||||
|
||||
|
||||
|
||||
test-attachment-validation: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestAttachment(ImageValidation|FilenameValidation|ValidationHTTP|MessageRequiresStringText)$$'
|
||||
|
||||
test-attachment-access: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestAttachmentAccess'
|
||||
|
||||
test-upload-recovery: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestUpload(Recovery|CrashHelper)'
|
||||
|
||||
test-attachment-cleanup: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestAttachmentCleanup'
|
||||
|
||||
test-s3-permissions: app-init
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests go test -race -count=1 -v ./backend/tests -run '^TestS3Permissions'
|
||||
$(PYTHON) scripts/check_s3_isolation.py
|
||||
|
||||
test-upload-memory:
|
||||
$(PYTHON) scripts/check_upload_memory.py
|
||||
|
||||
+45
-4
@@ -79,14 +79,18 @@ services:
|
||||
networks: [data]
|
||||
build: ./src
|
||||
environment: &s3-environment
|
||||
S3_ROOT_ACCESS_KEY_ID_FILE: /run/secrets/s3_root_access_key_id
|
||||
S3_ROOT_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_root_secret_access_key
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: ${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}
|
||||
S3_SECRET_ACCESS_KEY_FILE: ${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}
|
||||
volumes:
|
||||
- ./secrets/s3_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/s3_access_key_id:/run/secrets/s3_root_access_key_id:ro
|
||||
- ./secrets/s3_secret_access_key:/run/secrets/s3_root_secret_access_key:ro
|
||||
- ./secrets/s3_api_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_api_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
command: ["./messenger", "s3-bootstrap"]
|
||||
depends_on:
|
||||
s3:
|
||||
@@ -101,6 +105,10 @@ services:
|
||||
stop_grace_period: 15s
|
||||
environment:
|
||||
<<: *s3-environment
|
||||
S3_ROOT_ACCESS_KEY_ID_FILE: ""
|
||||
S3_ROOT_SECRET_ACCESS_KEY_FILE: ""
|
||||
UPLOAD_TMP_DIR: /tmp/uploads
|
||||
UPLOAD_CLEANUP_GRACE_SECONDS: ${UPLOAD_CLEANUP_GRACE_SECONDS:-600}
|
||||
# Go 1.22 sees host CPUs; keep parallelism suitable for this 0.5 CPU limit.
|
||||
GOMAXPROCS: ${API_GOMAXPROCS:-1}
|
||||
GOMEMLIMIT: 384MiB
|
||||
@@ -113,9 +121,11 @@ services:
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
REDIS_ADDR: redis:6379
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
tmpfs:
|
||||
- /tmp/uploads:rw,noexec,nosuid,size=16m,mode=1777
|
||||
volumes:
|
||||
- ./secrets/s3_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/s3_api_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_api_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/database_url:${DATABASE_URL_FILE:-/run/secrets/database_url}:ro
|
||||
- ./secrets/cache_url:${CACHE_URL_FILE:-/run/secrets/cache_url}:ro
|
||||
depends_on:
|
||||
@@ -132,6 +142,29 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
upload-cleanup:
|
||||
restart: unless-stopped
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
networks: [data]
|
||||
build: ./src
|
||||
command: ["./messenger", "attachments-cleanup", "--loop"]
|
||||
environment:
|
||||
<<: *s3-environment
|
||||
S3_ROOT_ACCESS_KEY_ID_FILE: ""
|
||||
S3_ROOT_SECRET_ACCESS_KEY_FILE: ""
|
||||
DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url}
|
||||
volumes:
|
||||
- ./secrets/s3_api_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_api_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/database_url:${DATABASE_URL_FILE:-/run/secrets/database_url}:ro
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
haproxy:
|
||||
environment:
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
@@ -170,9 +203,17 @@ services:
|
||||
context: ./src
|
||||
target: builder
|
||||
environment:
|
||||
<<: *s3-environment
|
||||
TEST_DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
TEST_REDIS_ADDR: redis:6379
|
||||
volumes:
|
||||
- ./secrets/s3_api_access_key_id:${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id}:ro
|
||||
- ./secrets/s3_api_secret_access_key:${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key}:ro
|
||||
- ./secrets/s3_access_key_id:/run/secrets/s3_root_access_key_id:ro
|
||||
- ./secrets/s3_secret_access_key:/run/secrets/s3_root_secret_access_key:ro
|
||||
depends_on:
|
||||
s3-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
db:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
services:
|
||||
haproxy:
|
||||
ports: !override
|
||||
- "127.0.0.1:18080:8080"
|
||||
- "127.0.0.1:18404:8404"
|
||||
frontend:
|
||||
profiles: [interactive]
|
||||
+244
-44
@@ -18,11 +18,22 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run
|
||||
|
||||
COMPOSE = ["docker", "compose", "--project-name", "highload-lab4", "--env-file", ".env", "-f", "compose.yml"]
|
||||
COMPOSE = [
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
"highload-lab4",
|
||||
"--env-file",
|
||||
".env",
|
||||
"-f",
|
||||
"compose.yml",
|
||||
]
|
||||
|
||||
|
||||
def command(args, **kwargs):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
|
||||
|
||||
|
||||
def ready(client):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
@@ -33,6 +44,7 @@ def ready(client):
|
||||
time.sleep(1)
|
||||
raise AssertionError("readiness did not recover")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
@@ -42,66 +54,169 @@ def main():
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments"
|
||||
def upload(data=png, mime="image/png", filename="photo.png", status=201, actor=alice, target=path):
|
||||
return c.call("POST", target + "?" + urllib.parse.urlencode({"filename": filename}), status,
|
||||
actor=actor, raw=data, headers={"Content-Type": mime}, schema="Attachment" if status == 201 else None)
|
||||
jpeg = base64.b64decode('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAACAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDj6KKKyPJP/9k=')
|
||||
jpeg_result = upload(data=jpeg,mime="image/jpeg",filename="photo.jpg")["json"]
|
||||
check(c.call("GET", "/api/v1/attachments/"+jpeg_result["id"]+"/content",actor=bob)["bytes"] == jpeg,"JPEG changed")
|
||||
|
||||
def upload(
|
||||
data=png,
|
||||
mime="image/png",
|
||||
filename="photo.png",
|
||||
status=201,
|
||||
actor=alice,
|
||||
target=path,
|
||||
):
|
||||
return c.call(
|
||||
"POST",
|
||||
target + "?" + urllib.parse.urlencode({"filename": filename}),
|
||||
status,
|
||||
actor=actor,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if status == 201 else None,
|
||||
)
|
||||
|
||||
jpeg = base64.b64decode(
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAACAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDj6KKKyPJP/9k="
|
||||
)
|
||||
jpeg_result = upload(data=jpeg, mime="image/jpeg", filename="photo.jpg")["json"]
|
||||
check(
|
||||
c.call(
|
||||
"GET", "/api/v1/attachments/" + jpeg_result["id"] + "/content", actor=bob
|
||||
)["bytes"]
|
||||
== jpeg,
|
||||
"JPEG changed",
|
||||
)
|
||||
first = upload()["json"]
|
||||
second = upload(filename="Второе фото.png")["json"]
|
||||
for a in (first, second):
|
||||
content = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
|
||||
content = c.call(
|
||||
"GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob
|
||||
)
|
||||
check(content["bytes"] == png, "download bytes changed")
|
||||
check(a["sha256"] == hashlib.sha256(png).hexdigest(), "checksum differs")
|
||||
for suffix in ("", "/content"):
|
||||
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 404, actor=eve)
|
||||
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 401)
|
||||
c.call("GET", "/api/v1/attachments/" + first["id"] + "/content?variant=thumbnail", 404, actor=alice)
|
||||
c.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + first["id"] + "/content?variant=thumbnail",
|
||||
404,
|
||||
actor=alice,
|
||||
)
|
||||
upload(actor=eve, status=404)
|
||||
upload(data=b"x" * (10485760 + 1), status=413)
|
||||
upload(data=png[:40], status=415)
|
||||
upload(mime="image/jpeg", status=415)
|
||||
upload(mime="text/plain", status=415)
|
||||
for filename in ("", " ", "../file.png", "a\\b.png", "a\x00.png", "a\n.png", "x" * 256):
|
||||
for filename in (
|
||||
"",
|
||||
" ",
|
||||
"../file.png",
|
||||
"a\\b.png",
|
||||
"a\x00.png",
|
||||
"a\n.png",
|
||||
"x" * 256,
|
||||
):
|
||||
upload(filename=filename, status=400)
|
||||
huge = bytearray(png)
|
||||
huge[16:24] = struct.pack(">II", 10001, 4000)
|
||||
huge[29:33] = struct.pack(">I", zlib.crc32(huge[12:29]) & 0xffffffff)
|
||||
huge[29:33] = struct.pack(">I", zlib.crc32(huge[12:29]) & 0xFFFFFFFF)
|
||||
upload(data=bytes(huge), status=413)
|
||||
|
||||
# Unknown-length uploads must obey the same byte limit.
|
||||
endpoint = urllib.parse.urlsplit(args.base_url)
|
||||
conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port or 80, timeout=35)
|
||||
conn.request("POST", path + "?filename=chunked.png", body=iter([png, b"x" * 10485760]),
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"}, encode_chunked=True)
|
||||
conn = http.client.HTTPConnection(
|
||||
endpoint.hostname, endpoint.port or 80, timeout=35
|
||||
)
|
||||
conn.request(
|
||||
"POST",
|
||||
path + "?filename=chunked.png",
|
||||
body=iter([png, b"x" * 10485760]),
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Content-Type": "image/png",
|
||||
},
|
||||
encode_chunked=True,
|
||||
)
|
||||
response = conn.getresponse()
|
||||
check(response.status == 413, "chunked body limit not enforced")
|
||||
response.read(); conn.close()
|
||||
response.read()
|
||||
conn.close()
|
||||
|
||||
ids = [first["id"], second["id"]]
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
def send(_):
|
||||
return c.message(alice, chat, "", key=key, attachments=ids)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
responses = list(pool.map(send, range(24)))
|
||||
check(len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2, "did not use two API replicas")
|
||||
check(all(r["json"] == responses[0]["json"] for r in responses), "replay changed message")
|
||||
check(
|
||||
len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2,
|
||||
"did not use two API replicas",
|
||||
)
|
||||
check(
|
||||
all(r["json"] == responses[0]["json"] for r in responses),
|
||||
"replay changed message",
|
||||
)
|
||||
messages_path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
history = c.call("GET", messages_path, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(len(history) == 1 and history[0]["attachment_ids"] == ids, "duplicate or lost attachments")
|
||||
for body, expected in (({"text": "", "attachment_ids": ids[::-1]}, 409),
|
||||
({"text": "changed", "attachment_ids": ids}, 409)):
|
||||
c.call("POST", messages_path, expected, actor=alice, body=body, headers={"Idempotency-Key": key})
|
||||
for bad_ids, expected in (([first["id"], first["id"]], 400), ([str(uuid.uuid4())], 404), (["invalid"], 400), (None, 400), (ids * 6, 400)):
|
||||
c.call("POST", messages_path, expected, actor=alice, body={"text": "x", "attachment_ids": bad_ids}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Other", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
c.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=alice,
|
||||
body={"text": "", "attachment_ids": [first["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
history = c.call("GET", messages_path, actor=bob, schema="MessagePage")["json"][
|
||||
"items"
|
||||
]
|
||||
check(
|
||||
len(history) == 1 and history[0]["attachment_ids"] == ids,
|
||||
"duplicate or lost attachments",
|
||||
)
|
||||
for body, expected in (
|
||||
({"text": "", "attachment_ids": ids[::-1]}, 409),
|
||||
({"text": "changed", "attachment_ids": ids}, 409),
|
||||
):
|
||||
c.call(
|
||||
"POST",
|
||||
messages_path,
|
||||
expected,
|
||||
actor=alice,
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
for bad_ids, expected in (
|
||||
([first["id"], first["id"]], 400),
|
||||
([str(uuid.uuid4())], 404),
|
||||
(["invalid"], 400),
|
||||
(None, 400),
|
||||
(ids * 6, 400),
|
||||
):
|
||||
c.call(
|
||||
"POST",
|
||||
messages_path,
|
||||
expected,
|
||||
actor=alice,
|
||||
body={"text": "x", "attachment_ids": bad_ids},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
other_chat = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Other", "member_ids": [alice["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other_chat["id"] + "/messages",
|
||||
404,
|
||||
actor=alice,
|
||||
body={"text": "", "attachment_ids": [first["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
text_key = uuid.uuid4().hex
|
||||
text = c.message(alice, chat, "text", key=text_key)["json"]
|
||||
check(c.message(alice, chat, "text", key=text_key, attachments=[])["json"] == text, "omitted/empty array differ")
|
||||
print("PASS: image limits, chunked upload, ACL, message attachments, concurrent replay across replicas")
|
||||
check(
|
||||
c.message(alice, chat, "text", key=text_key, attachments=[])["json"] == text,
|
||||
"omitted/empty array differ",
|
||||
)
|
||||
print(
|
||||
"PASS: image limits, chunked upload, ACL, message attachments, concurrent replay across replicas"
|
||||
)
|
||||
|
||||
if args.failures:
|
||||
records = []
|
||||
@@ -109,51 +224,135 @@ def main():
|
||||
result = upload()
|
||||
target = result["headers"]["X-Instance-Id"]
|
||||
a = result["json"]
|
||||
check(not records or target != records[0]["upload_instance"], "repeat did not target the other replica")
|
||||
check(
|
||||
not records or target != records[0]["upload_instance"],
|
||||
"repeat did not target the other replica",
|
||||
)
|
||||
try:
|
||||
command([str(ROOT / "scripts/stop-one.sh")], env={**os.environ, "TARGET_INSTANCE_ID": target})
|
||||
command(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": target},
|
||||
)
|
||||
time.sleep(3)
|
||||
downloaded = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
|
||||
downloaded = c.call(
|
||||
"GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob
|
||||
)
|
||||
check(downloaded["bytes"] == png, "original lost across failover")
|
||||
served = downloaded["headers"]["X-Instance-Id"]
|
||||
check(served != target, "download came from stopped instance")
|
||||
records.append({"upload_instance": target, "download_instance": served, "sha256": a["sha256"]})
|
||||
records.append(
|
||||
{
|
||||
"upload_instance": target,
|
||||
"download_instance": served,
|
||||
"sha256": a["sha256"],
|
||||
}
|
||||
)
|
||||
if len(records) == 1:
|
||||
# Upload the next fixture while only the second replica runs.
|
||||
# Restore below, then select that same replica via LB uploads.
|
||||
next_target = served
|
||||
finally:
|
||||
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
|
||||
command(
|
||||
COMPOSE + ["up", "-d", "--no-build", "--wait"],
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
ready(c)
|
||||
if len(records) == 1:
|
||||
# Round-robin state may change after recovery; keep requesting until it
|
||||
# chooses the other replica, then use that upload in the next pass.
|
||||
original_upload = upload
|
||||
|
||||
def upload(*a, **kw):
|
||||
for attempt in range(30):
|
||||
candidate = original_upload(*a, **kw)
|
||||
if candidate["headers"]["X-Instance-Id"] == next_target:
|
||||
return candidate
|
||||
raise AssertionError("could not reach second replica")
|
||||
print("PASS: stop the uploading replica, download from the other (both replicas)")
|
||||
|
||||
print(
|
||||
"PASS: stop the uploading replica, download from the other (both replicas)"
|
||||
)
|
||||
try:
|
||||
command(COMPOSE + ["stop", "s3"], stderr=subprocess.STDOUT)
|
||||
# Probe through an existing image on the data network; no API port exposure.
|
||||
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
|
||||
probe = ["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}"]
|
||||
image = command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{.Config.Image}}",
|
||||
command(COMPOSE + ["ps", "--all", "-q", "s3"]),
|
||||
]
|
||||
)
|
||||
probe = [
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--network",
|
||||
"highload-lab4_data",
|
||||
"--entrypoint",
|
||||
"curl",
|
||||
image,
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
]
|
||||
for container in command(COMPOSE + ["ps", "-q", "api"]).splitlines():
|
||||
# Container hostname aliases are not DNS names; use the data-network IP.
|
||||
info = json.loads(command(["docker", "inspect", container]))[0]
|
||||
ip = info["NetworkSettings"]["Networks"]["highload-lab4_data"]["IPAddress"]
|
||||
check(command(probe + [f"http://{ip}:8080/health/live"]) == "200", "liveness depends on S3")
|
||||
check(command(probe + [f"http://{ip}:8080/health/ready"]) == "503", "readiness ignores S3 failure")
|
||||
ip = info["NetworkSettings"]["Networks"]["highload-lab4_data"][
|
||||
"IPAddress"
|
||||
]
|
||||
check(
|
||||
command(probe + [f"http://{ip}:8080/health/live"]) == "200",
|
||||
"liveness depends on S3",
|
||||
)
|
||||
check(
|
||||
command(probe + [f"http://{ip}:8080/health/ready"]) == "503",
|
||||
"readiness ignores S3 failure",
|
||||
)
|
||||
records.append({"s3_failure": "live=200 ready=503 on both API replicas"})
|
||||
finally:
|
||||
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
|
||||
command(
|
||||
COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT
|
||||
)
|
||||
ready(c)
|
||||
check(c.call("GET", "/api/v1/attachments/" + first["id"] + "/content", actor=bob)["bytes"] == png, "S3 recovery lost bytes")
|
||||
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
|
||||
code = command(["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}", "http://s3:9000/messenger-attachments/originals/" + first["id"]])
|
||||
check(
|
||||
c.call("GET", "/api/v1/attachments/" + first["id"] + "/content", actor=bob)[
|
||||
"bytes"
|
||||
]
|
||||
== png,
|
||||
"S3 recovery lost bytes",
|
||||
)
|
||||
image = command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{.Config.Image}}",
|
||||
command(COMPOSE + ["ps", "--all", "-q", "s3"]),
|
||||
]
|
||||
)
|
||||
code = command(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--network",
|
||||
"highload-lab4_data",
|
||||
"--entrypoint",
|
||||
"curl",
|
||||
image,
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"http://s3:9000/messenger-attachments/originals/" + first["id"],
|
||||
]
|
||||
)
|
||||
check(code == "403", "anonymous object access was permitted")
|
||||
records.append({"anonymous_object_get": code})
|
||||
directory = ROOT / ".memory/grade3"
|
||||
@@ -161,5 +360,6 @@ def main():
|
||||
(directory / "failures.json").write_text(json.dumps(records, indent=2) + "\n")
|
||||
print("PASS: S3 unavailable/recovery, private bucket")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def main():
|
||||
evidence = []
|
||||
for service in ("s3", "api", "upload-cleanup"):
|
||||
ids = command(["docker", "compose", "ps", "-q", service]).splitlines()
|
||||
assert ids, "service is not running: " + service
|
||||
for cid in ids:
|
||||
info = json.loads(command(["docker", "inspect", cid]))[0]
|
||||
sources = [
|
||||
Path(mount["Source"]).name
|
||||
for mount in info["Mounts"]
|
||||
if mount["Type"] == "bind"
|
||||
]
|
||||
if service == "s3":
|
||||
assert not info["HostConfig"]["PortBindings"], "S3 ports are published"
|
||||
assert "MINIO_BROWSER=off" in info["Config"]["Env"], (
|
||||
"MinIO console is enabled"
|
||||
)
|
||||
assert set(info["NetworkSettings"]["Networks"]) == {
|
||||
"highload-lab4_data"
|
||||
}
|
||||
else:
|
||||
assert (
|
||||
"s3_access_key_id" not in sources
|
||||
and "s3_secret_access_key" not in sources
|
||||
), "root credentials mounted into " + service
|
||||
assert (
|
||||
"s3_api_access_key_id" in sources
|
||||
and "s3_api_secret_access_key" in sources
|
||||
)
|
||||
if service == "api":
|
||||
assert (
|
||||
info["HostConfig"]["Tmpfs"]["/tmp/uploads"].find("size=16m") >= 0
|
||||
), "upload tmpfs limit missing"
|
||||
assert info["HostConfig"]["Memory"] == 512 * 1048576
|
||||
evidence.append(
|
||||
{
|
||||
"service": service,
|
||||
"container": info["Config"]["Hostname"],
|
||||
"bind_filenames": sources,
|
||||
"published_ports": info["HostConfig"]["PortBindings"],
|
||||
"tmpfs": info["HostConfig"].get("Tmpfs", {}),
|
||||
}
|
||||
)
|
||||
directory = ROOT / ".memory/s3-permissions"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "isolation.json").write_text(json.dumps(evidence, indent=2) + "\n")
|
||||
print(
|
||||
"PASS: private S3 network, disabled console, restricted API mounts, bounded tmpfs"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,381 @@
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
LIMIT = 512 * 1024 * 1024
|
||||
SIZE = 10485760
|
||||
BASE_URL = "http://127.0.0.1:18080"
|
||||
|
||||
|
||||
def command(args, **kwargs):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
|
||||
|
||||
|
||||
def png(width, height):
|
||||
def chunk(kind, data):
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ kind
|
||||
+ data
|
||||
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
compressor = zlib.compressobj(6)
|
||||
row = b"\0" + bytes((20, 100, 50)) * width
|
||||
compressed = (
|
||||
b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||||
)
|
||||
data = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", compressed)
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
return data + b"\0" * (SIZE - len(data))
|
||||
|
||||
|
||||
def inspect(ids):
|
||||
data = json.loads(command(["docker", "inspect", *ids]))
|
||||
return [
|
||||
{
|
||||
"id": item["Id"],
|
||||
"started_at": item["State"]["StartedAt"],
|
||||
"image": item["Image"],
|
||||
"restarts": item["RestartCount"],
|
||||
"oom_killed": item["State"]["OOMKilled"],
|
||||
"memory_limit": item["HostConfig"]["Memory"],
|
||||
"cpus": item["HostConfig"]["NanoCpus"],
|
||||
}
|
||||
for item in data
|
||||
]
|
||||
|
||||
|
||||
def cgroup(container):
|
||||
text = command(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
container,
|
||||
"sh",
|
||||
"-c",
|
||||
"cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory.events",
|
||||
]
|
||||
)
|
||||
lines = text.splitlines()
|
||||
return {
|
||||
"current": int(lines[0]),
|
||||
"peak": int(lines[1]),
|
||||
"limit": int(lines[2]),
|
||||
"events": {line.split()[0]: int(line.split()[1]) for line in lines[3:]},
|
||||
}
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self, ids, path):
|
||||
self.file = path.open("w")
|
||||
self.lock = threading.Lock()
|
||||
self.processes = []
|
||||
self.threads = []
|
||||
self.counts = {cid: 0 for cid in ids}
|
||||
self.errors = []
|
||||
script = 'while true; do read current < /sys/fs/cgroup/memory.current; read peak < /sys/fs/cgroup/memory.peak; printf \'%s %s\\n\' "$current" "$peak"; sleep 0.1; done'
|
||||
for cid in ids:
|
||||
process = subprocess.Popen(
|
||||
["docker", "exec", cid, "sh", "-c", script],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
self.processes.append(process)
|
||||
thread = threading.Thread(
|
||||
target=self.read, args=(cid, process), daemon=True
|
||||
)
|
||||
thread.start()
|
||||
self.threads.append(thread)
|
||||
|
||||
def read(self, cid, process):
|
||||
try:
|
||||
for line in process.stdout:
|
||||
current, peak = map(int, line.split())
|
||||
with self.lock:
|
||||
self.counts[cid] += 1
|
||||
self.file.write(
|
||||
json.dumps(
|
||||
{
|
||||
"container": cid,
|
||||
"monotonic_ns": time.monotonic_ns(),
|
||||
"current": current,
|
||||
"peak": peak,
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
self.file.flush()
|
||||
except Exception as error:
|
||||
self.errors.append(str(error))
|
||||
|
||||
def close(self):
|
||||
for process in self.processes:
|
||||
process.terminate()
|
||||
for process in self.processes:
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
for thread in self.threads:
|
||||
thread.join(timeout=5)
|
||||
self.file.close()
|
||||
|
||||
|
||||
def verify_content(actor, attachment, digest):
|
||||
request = urllib.request.Request(
|
||||
BASE_URL + "/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
headers={"Authorization": "Bearer " + actor["token"]},
|
||||
)
|
||||
checksum = hashlib.sha256()
|
||||
size = 0
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
for chunk in iter(lambda: response.read(65536), b""):
|
||||
checksum.update(chunk)
|
||||
size += len(chunk)
|
||||
if checksum.hexdigest() != digest or size != SIZE:
|
||||
raise AssertionError("download differs from original")
|
||||
|
||||
|
||||
def run_case(compose, profile, data, directory):
|
||||
client = Client(BASE_URL, timeout=45)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=memory.png"
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
for _ in range(2):
|
||||
client.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
ids = command(compose + ["ps", "-q", "api"]).splitlines()
|
||||
if len(ids) != 2:
|
||||
raise AssertionError("expected two API containers")
|
||||
before = inspect(ids)
|
||||
baseline = {cid: cgroup(cid) for cid in ids}
|
||||
(directory / "before.json").write_text(
|
||||
json.dumps({"containers": before, "cgroups": baseline}, indent=2) + "\n"
|
||||
)
|
||||
sampler = Sampler(ids, directory / "samples.jsonl")
|
||||
barrier = threading.Barrier(11)
|
||||
results = []
|
||||
|
||||
def upload(index):
|
||||
barrier.wait()
|
||||
started = time.monotonic_ns()
|
||||
try:
|
||||
response = client.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
return {
|
||||
"client": index,
|
||||
"started_ns": started,
|
||||
"ended_ns": time.monotonic_ns(),
|
||||
"ok": True,
|
||||
"instance": response["headers"]["X-Instance-Id"],
|
||||
"attachment": response["json"],
|
||||
}
|
||||
except Exception as error:
|
||||
return {
|
||||
"client": index,
|
||||
"started_ns": started,
|
||||
"ended_ns": time.monotonic_ns(),
|
||||
"ok": False,
|
||||
"error": str(error),
|
||||
}
|
||||
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(upload, index) for index in range(10)]
|
||||
barrier.wait()
|
||||
results = [future.result() for future in futures]
|
||||
finally:
|
||||
sampler.close()
|
||||
# Save responses before probing containers, including when an OOM stopped one.
|
||||
(directory / "requests.json").write_text(json.dumps(results, indent=2) + "\n")
|
||||
after = inspect(ids)
|
||||
(directory / "after.json").write_text(json.dumps(after, indent=2) + "\n")
|
||||
final = {cid: cgroup(cid) for cid in ids}
|
||||
for result in results:
|
||||
if result["ok"]:
|
||||
try:
|
||||
verify_content(bob, result["attachment"], digest)
|
||||
result["original_verified"] = True
|
||||
except Exception as error:
|
||||
result["original_verified"] = False
|
||||
result["verification_error"] = str(error)
|
||||
passed = (
|
||||
len(results) == 10
|
||||
and all(r["ok"] and r.get("original_verified") for r in results)
|
||||
and len({r.get("instance") for r in results}) == 2
|
||||
and before == after
|
||||
and all(not r["oom_killed"] for r in after)
|
||||
and all(
|
||||
final[cid]["peak"] < LIMIT
|
||||
and final[cid]["limit"] == LIMIT
|
||||
and final[cid]["events"].get("oom_kill", 0)
|
||||
== baseline[cid]["events"].get("oom_kill", 0)
|
||||
and final[cid]["events"].get("oom", 0)
|
||||
== baseline[cid]["events"].get("oom", 0)
|
||||
for cid in ids
|
||||
)
|
||||
and all(count > 0 for count in sampler.counts.values())
|
||||
and not sampler.errors
|
||||
)
|
||||
summary = {
|
||||
"profile": profile,
|
||||
"passed": passed,
|
||||
"before": before,
|
||||
"after": after,
|
||||
"baseline": baseline,
|
||||
"final": final,
|
||||
"sample_counts": sampler.counts,
|
||||
"sampler_errors": sampler.errors,
|
||||
"requests": results,
|
||||
}
|
||||
(directory / "results.json").write_text(json.dumps(summary, indent=2) + "\n")
|
||||
return {
|
||||
"profile": profile,
|
||||
"passed": passed,
|
||||
"peaks_mib": [round(final[cid]["peak"] / 1048576, 2) for cid in ids],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
import fcntl
|
||||
|
||||
directory = (
|
||||
ROOT
|
||||
/ ".memory/upload-memory"
|
||||
/ datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
)
|
||||
directory.mkdir(parents=True)
|
||||
lock = (ROOT / ".memory/upload-memory.lock").open("w")
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
fixtures = {"moderate": png(320, 200), "pixels40m": png(8000, 5000)}
|
||||
files = (
|
||||
[
|
||||
ROOT / "compose.yml",
|
||||
ROOT / "infra/compose.upload-memory.yml",
|
||||
ROOT / "infra/minio.Dockerfile",
|
||||
ROOT / "infra/haproxy.cfg",
|
||||
ROOT / "src/Dockerfile",
|
||||
ROOT / "src/go.mod",
|
||||
ROOT / "src/go.sum",
|
||||
Path(__file__),
|
||||
]
|
||||
+ sorted((ROOT / "src/backend").rglob("*.go"))
|
||||
+ sorted((ROOT / "src/backend").rglob("*.sql"))
|
||||
)
|
||||
hashes = {
|
||||
str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in files
|
||||
}
|
||||
protocol = {
|
||||
"version": 1,
|
||||
"hypothesis": "10 concurrent upload requests remain within 512 MiB per API with no OOM or restarts and all originals preserved",
|
||||
"clients": 10,
|
||||
"api_replicas": 2,
|
||||
"cpu_per_api": 0.5,
|
||||
"memory_limit_bytes": LIMIT,
|
||||
"tmpfs_bytes": 16777216,
|
||||
"active_uploads_per_replica": 1,
|
||||
"sampling_interval_seconds": 0.1,
|
||||
"repetitions": 3,
|
||||
"warmup_uploads": 2,
|
||||
"request_timeout_seconds": 45,
|
||||
"model": "one simultaneous burst of 10 requests, no retries",
|
||||
"order": [profile for _ in range(3) for profile in fixtures],
|
||||
"fixtures": {
|
||||
name: {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
|
||||
for name, data in fixtures.items()
|
||||
},
|
||||
"isolation": "fresh Compose project and volumes per run; same code/resources; no parallel fault tests",
|
||||
"criteria": "all 60 measured uploads and downloads succeed; both replicas used; cgroup peak strictly below limit; no OOM/restart",
|
||||
"insufficient_data": "sampler failure or missing samples; retain run as inconclusive, never discard errors/OOM",
|
||||
"stop_rules": "complete all six runs even on failed request or OOM; no favorable early stop",
|
||||
"limitations": "one host; concurrent HTTP requests with at most two decoders; tmpfs counted in cgroup; sampler overhead",
|
||||
"source_sha256": hashes,
|
||||
}
|
||||
serialized = json.dumps(protocol, indent=2).encode() + b"\n"
|
||||
(directory / "protocol.json").write_bytes(serialized)
|
||||
(directory / "protocol.sha256").write_text(
|
||||
hashlib.sha256(serialized).hexdigest() + "\n"
|
||||
)
|
||||
print("Protocol fixed:", directory, flush=True)
|
||||
summaries = []
|
||||
stamp = directory.name.lower().replace("t", "").replace("z", "")
|
||||
for index, profile in enumerate(protocol["order"], 1):
|
||||
run = directory / f"{index:02d}-{profile}"
|
||||
run.mkdir()
|
||||
project = f"highload-lab4-upload-memory-{stamp}-{index}"
|
||||
compose = [
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
project,
|
||||
"--env-file",
|
||||
".env",
|
||||
"-f",
|
||||
"compose.yml",
|
||||
"-f",
|
||||
"infra/compose.upload-memory.yml",
|
||||
]
|
||||
(run / "project.txt").write_text(project + "\n")
|
||||
try:
|
||||
with (run / "startup.log").open("w") as log:
|
||||
subprocess.run(
|
||||
compose + ["up", "-d", "--build", "--wait"],
|
||||
cwd=ROOT,
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
check=True,
|
||||
)
|
||||
summary = run_case(compose, profile, fixtures[profile], run)
|
||||
except Exception as error:
|
||||
summary = {"profile": profile, "passed": False, "error": str(error)}
|
||||
(run / "failure.json").write_text(json.dumps(summary, indent=2) + "\n")
|
||||
finally:
|
||||
with (run / "shutdown.log").open("w") as log:
|
||||
subprocess.run(
|
||||
compose + ["down"], cwd=ROOT, stdout=log, stderr=subprocess.STDOUT
|
||||
)
|
||||
summaries.append(summary)
|
||||
print(json.dumps(summary), flush=True)
|
||||
(directory / "summary.json").write_text(json.dumps(summaries, indent=2) + "\n")
|
||||
if not all(case["passed"] for case in summaries):
|
||||
raise SystemExit(1)
|
||||
print("PASS: all six upload-memory runs", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+54
-14
@@ -5,6 +5,7 @@ from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def read_values(path):
|
||||
values = {}
|
||||
if path.exists():
|
||||
@@ -15,23 +16,37 @@ def read_values(path):
|
||||
values[key.strip()] = value.strip().strip("\"'")
|
||||
return values
|
||||
|
||||
|
||||
def main():
|
||||
path = ROOT / ".env"
|
||||
existing = read_values(path)
|
||||
defaults = read_values(ROOT / ".env.example")
|
||||
defaults.update(POSTGRES_DB="messenger", POSTGRES_USER="messenger",
|
||||
POSTGRES_PASSWORD=secrets.token_hex(24))
|
||||
defaults.update(
|
||||
POSTGRES_DB="messenger",
|
||||
POSTGRES_USER="messenger",
|
||||
POSTGRES_PASSWORD=secrets.token_hex(24),
|
||||
)
|
||||
defaults.update(UPLOAD_CLEANUP_GRACE_SECONDS="600", UPLOAD_TMP_DIR="/tmp/uploads")
|
||||
values = defaults | existing
|
||||
for name, lower, upper in (("APP_PORT", 1, 65535), ("API_REPLICAS", 2, 32),
|
||||
("SESSION_TTL_SECONDS", 1, 31536000),
|
||||
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000)):
|
||||
for name, lower, upper in (
|
||||
("APP_PORT", 1, 65535),
|
||||
("API_REPLICAS", 2, 32),
|
||||
("SESSION_TTL_SECONDS", 1, 31536000),
|
||||
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000),
|
||||
):
|
||||
try:
|
||||
valid = lower <= int(values[name]) <= upper
|
||||
except (ValueError, KeyError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise SystemExit(f"{name} must be between {lower} and {upper}")
|
||||
for name in ("POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD", "APP_HOST", "APP_ENV"):
|
||||
for name in (
|
||||
"POSTGRES_DB",
|
||||
"POSTGRES_USER",
|
||||
"POSTGRES_PASSWORD",
|
||||
"APP_HOST",
|
||||
"APP_ENV",
|
||||
):
|
||||
if not values[name]:
|
||||
raise SystemExit(f"{name} must not be empty")
|
||||
# Existing values, including credentials, are never replaced.
|
||||
@@ -39,28 +54,53 @@ def main():
|
||||
if missing:
|
||||
prefix = "\n" if path.exists() and path.stat().st_size else ""
|
||||
with path.open("a", encoding="utf-8") as file:
|
||||
file.write(prefix + "".join(f"{key}={value}\n" for key, value in missing.items()))
|
||||
file.write(
|
||||
prefix + "".join(f"{key}={value}\n" for key, value in missing.items())
|
||||
)
|
||||
os.chmod(path, 0o600)
|
||||
secret_dir = ROOT / "secrets"
|
||||
secret_dir.mkdir(mode=0o700, exist_ok=True)
|
||||
database_url = "postgres://{}:{}@db:5432/{}?sslmode=disable".format(
|
||||
quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""),
|
||||
quote(values["POSTGRES_DB"], safe=""))
|
||||
for name, content in (("DATABASE_URL_FILE", database_url),
|
||||
("CACHE_URL_FILE", "redis://redis:6379/0"),
|
||||
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
|
||||
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32))):
|
||||
quote(values["POSTGRES_USER"], safe=""),
|
||||
quote(values["POSTGRES_PASSWORD"], safe=""),
|
||||
quote(values["POSTGRES_DB"], safe=""),
|
||||
)
|
||||
for name, content in (
|
||||
("DATABASE_URL_FILE", database_url),
|
||||
("CACHE_URL_FILE", "redis://redis:6379/0"),
|
||||
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
|
||||
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32)),
|
||||
):
|
||||
container_path = Path(values[name])
|
||||
if container_path.parent != Path("/run/secrets") or not container_path.name:
|
||||
raise SystemExit(f"{name} must name a file directly inside /run/secrets")
|
||||
target = secret_dir / {"DATABASE_URL_FILE":"database_url", "CACHE_URL_FILE":"cache_url", "S3_ACCESS_KEY_ID_FILE":"s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE":"s3_secret_access_key"}[name]
|
||||
target = (
|
||||
secret_dir
|
||||
/ {
|
||||
"DATABASE_URL_FILE": "database_url",
|
||||
"CACHE_URL_FILE": "cache_url",
|
||||
"S3_ACCESS_KEY_ID_FILE": "s3_access_key_id",
|
||||
"S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key",
|
||||
}[name]
|
||||
)
|
||||
if not target.exists():
|
||||
# Containers run as an unprivileged user; the private host directory
|
||||
# protects the files, while read permission lets the API consume them.
|
||||
with target.open("x", encoding="utf-8") as file:
|
||||
file.write(content + "\n")
|
||||
os.chmod(target, 0o644)
|
||||
# Existing S3 files remain the root credentials; API gets a new, separate identity.
|
||||
for filename, content in (
|
||||
("s3_api_access_key_id", secrets.token_hex(12)),
|
||||
("s3_api_secret_access_key", secrets.token_hex(32)),
|
||||
):
|
||||
target = secret_dir / filename
|
||||
if not target.exists():
|
||||
with target.open("x", encoding="utf-8") as file:
|
||||
file.write(content + "\n")
|
||||
os.chmod(target, 0o644)
|
||||
print("Local .env and connection files ready; existing values and files preserved.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
+1
-1
@@ -3,5 +3,5 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart db redis s3 >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait db redis s3 >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api upload-cleanup >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait >/dev/null
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func runUploadCleanup(args []string) error {
|
||||
flags := flag.NewFlagSet("attachments-cleanup", flag.ContinueOnError)
|
||||
loop := flags.Bool("loop", false, "run every 60 seconds")
|
||||
dryRun := flags.Bool("dry-run", false, "report without deleting anything")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
init, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
db, err := repositories.OpenDatabase(init)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store := repositories.NewAttachmentStore(db)
|
||||
for {
|
||||
pass, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
result, err := store.CleanupUploads(pass, *dryRun, objects.Delete)
|
||||
cancel()
|
||||
if encodeErr := json.NewEncoder(os.Stdout).Encode(result); encodeErr != nil {
|
||||
return encodeErr
|
||||
}
|
||||
if !*loop {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
log.Print("upload cleanup pass failed; journal retained for retry")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(60 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -36,18 +36,20 @@ func main() {
|
||||
log.SetPrefix("[" + environment + "] ")
|
||||
}
|
||||
if len(os.Args) == 2 && os.Args[1] == "s3-bootstrap" {
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err = objects.Bootstrap(ctx); err != nil {
|
||||
log.Fatal("S3 bootstrap failed")
|
||||
if err := repositories.BootstrapS3(ctx); err != nil {
|
||||
log.Fatal("S3 bootstrap failed: ", err)
|
||||
}
|
||||
log.Print("private S3 bucket ready")
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "attachments-cleanup" {
|
||||
if err := runUploadCleanup(os.Args[2:]); err != nil {
|
||||
log.Fatal("upload cleanup failed: ", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
@@ -78,6 +80,9 @@ func main() {
|
||||
log.Printf("migration %s complete", os.Args[2])
|
||||
return
|
||||
}
|
||||
if _, err := repositories.UploadCleanupGrace(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
db, err := repositories.OpenDatabase(ctx)
|
||||
cancel()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UploadCleanupGrace() (time.Duration, error) {
|
||||
value := os.Getenv("UPLOAD_CLEANUP_GRACE_SECONDS")
|
||||
if value == "" {
|
||||
value = "600"
|
||||
}
|
||||
seconds, err := strconv.Atoi(value)
|
||||
if err != nil || seconds < 120 || seconds > 86400 {
|
||||
return 0, errors.New("UPLOAD_CLEANUP_GRACE_SECONDS must be between 120 and 86400")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE upload_attempts;
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE upload_attempts (
|
||||
id uuid PRIMARY KEY,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
cleanup_after timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX upload_attempts_cleanup_idx ON upload_attempts(cleanup_after,id);
|
||||
@@ -0,0 +1,83 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
func readS3Secret(name string) (string, error) {
|
||||
data, err := os.ReadFile(os.Getenv(name))
|
||||
if err != nil {
|
||||
return "", errors.New("cannot read " + name)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", errors.New("empty " + name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// BootstrapS3 is the only application command that needs administrative credentials.
|
||||
func BootstrapS3(ctx context.Context) error {
|
||||
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
if err != nil || endpoint.Host == "" {
|
||||
return errors.New("invalid S3_ENDPOINT")
|
||||
}
|
||||
rootAccess, err := readS3Secret("S3_ROOT_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rootSecret, err := readS3Secret("S3_ROOT_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
access, err := readS3Secret("S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secret, err := readS3Secret("S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if access == rootAccess {
|
||||
return errors.New("API and root credentials must differ")
|
||||
}
|
||||
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(rootAccess, rootSecret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION")})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store := &ObjectStore{client: client, bucket: os.Getenv("S3_BUCKET")}
|
||||
if err = store.Bootstrap(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
admin, err := madmin.New(endpoint.Host, rootAccess, rootSecret, endpoint.Scheme == "https")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + store.bucket}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*"}},
|
||||
}}
|
||||
data, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
const name = "messenger-attachments-api"
|
||||
if err = admin.AddCannedPolicy(ctx, name, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = admin.SetUserReq(ctx, access, madmin.AddOrUpdateUserReq{SecretKey: secret, Status: madmin.AccountEnabled}); err != nil {
|
||||
return err
|
||||
}
|
||||
// Explicitly assign the managed policy; creating a user alone grants no S3 rights.
|
||||
// This idempotent API is supported by our pinned MinIO server release.
|
||||
return admin.SetPolicy(ctx, name, access, false)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ReserveUpload is committed before any S3 PUT, so an interrupted request is tracked.
|
||||
func (s *AttachmentStore) ReserveUpload(ctx context.Context, a Attachment, grace time.Duration) error {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
_, err := s.db.Exec(ctx, `INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()+$3*interval '1 second')`, a.ID, a.ObjectKey, grace.Seconds())
|
||||
return err
|
||||
}
|
||||
|
||||
// PublishUpload holds the journal row lock across PUT and metadata COMMIT.
|
||||
// Cleanup skips that row; a crash rolls back metadata but preserves the reservation.
|
||||
func (s *AttachmentStore) PublishUpload(ctx context.Context, a Attachment, put func(context.Context) error) error {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var key string
|
||||
err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after>clock_timestamp() FOR UPDATE`, a.ID).Scan(&key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if key != a.ObjectKey {
|
||||
return errors.New("upload reservation mismatch")
|
||||
}
|
||||
if err = put(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
type CleanupResult struct {
|
||||
Candidates int `json:"candidates"`
|
||||
Deleted int `json:"deleted"`
|
||||
Eligible int `json:"eligible"`
|
||||
Protected int `json:"protected"`
|
||||
Skipped int `json:"skipped"`
|
||||
Failed int `json:"failed"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
}
|
||||
|
||||
// CleanupUploads only visits journal entries; it never scans or deletes legacy data.
|
||||
func (s *AttachmentStore) CleanupUploads(ctx context.Context, dryRun bool, remove func(context.Context, string) error) (CleanupResult, error) {
|
||||
result := CleanupResult{DryRun: dryRun}
|
||||
rows, err := s.db.Query(ctx, `SELECT id::text FROM upload_attempts WHERE cleanup_after<=clock_timestamp() ORDER BY cleanup_after,id LIMIT 100`)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return result, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Candidates = len(ids)
|
||||
for _, id := range ids {
|
||||
outcome, err := s.cleanupUpload(ctx, id, dryRun, remove)
|
||||
if err != nil {
|
||||
result.Failed++
|
||||
continue
|
||||
}
|
||||
switch outcome {
|
||||
case "eligible":
|
||||
result.Eligible++
|
||||
case "deleted":
|
||||
result.Deleted++
|
||||
case "protected":
|
||||
result.Protected++
|
||||
default:
|
||||
result.Skipped++
|
||||
}
|
||||
}
|
||||
if result.Failed > 0 {
|
||||
return result, fmt.Errorf("%d upload cleanup operations failed", result.Failed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) cleanupUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var key string
|
||||
err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after<=clock_timestamp() FOR UPDATE SKIP LOCKED`, id).Scan(&key)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "skipped", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Restrict destructive actions to server-generated keys even if a journal row is malformed.
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || key != "originals/"+parsed.String() {
|
||||
return "", errors.New("invalid upload journal key")
|
||||
}
|
||||
var ready bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&ready); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if dryRun {
|
||||
if ready {
|
||||
return "protected", nil
|
||||
}
|
||||
return "eligible", nil
|
||||
}
|
||||
if !ready {
|
||||
// On DELETE failure retain the journal entry for the next pass.
|
||||
if err = remove(ctx, key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ready {
|
||||
return "protected", nil
|
||||
}
|
||||
return "deleted", nil
|
||||
}
|
||||
@@ -6,20 +6,20 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"mime"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const MaxUploadBytes int64 = 10485760
|
||||
@@ -31,11 +31,16 @@ var ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
|
||||
type AttachmentService struct {
|
||||
metadata *repositories.AttachmentStore
|
||||
objects *repositories.ObjectStore
|
||||
objects AttachmentObjects
|
||||
uploadSlot chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
|
||||
type AttachmentObjects interface {
|
||||
Put(context.Context, string, io.Reader, int64, string) error
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
func NewAttachmentService(metadata *repositories.AttachmentStore, objects AttachmentObjects) *AttachmentService {
|
||||
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
|
||||
}
|
||||
func ValidateFilename(name string) error {
|
||||
@@ -50,11 +55,15 @@ func ValidateFilename(name string) error {
|
||||
return nil
|
||||
}
|
||||
func ValidateImage(data []byte, declared string) (string, error) {
|
||||
return ValidateImageReader(bytes.NewReader(data), declared)
|
||||
}
|
||||
|
||||
func ValidateImageReader(reader io.ReadSeeker, declared string) (string, error) {
|
||||
contentType, _, err := mime.ParseMediaType(declared)
|
||||
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
config, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
config, format, err := image.DecodeConfig(reader)
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
@@ -66,7 +75,10 @@ func ValidateImage(data []byte, declared string) (string, error) {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
|
||||
decoded, _, err := image.Decode(bytes.NewReader(data))
|
||||
if _, err = reader.Seek(0, io.SeekStart); err != nil {
|
||||
return "", err
|
||||
}
|
||||
decoded, _, err := image.Decode(reader)
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
@@ -80,37 +92,55 @@ func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename
|
||||
case <-ctx.Done():
|
||||
return repositories.Attachment{}, ctx.Err()
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
|
||||
grace, err := repositories.UploadCleanupGrace()
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if int64(len(data)) > MaxUploadBytes {
|
||||
directory := os.Getenv("UPLOAD_TMP_DIR")
|
||||
file, err := os.CreateTemp(directory, "upload-*")
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
// Linux keeps the open descriptor usable; no abandoned pathname survives a crash.
|
||||
if err = os.Remove(file.Name()); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(body, MaxUploadBytes+1), make([]byte, 32*1024))
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if size > MaxUploadBytes {
|
||||
return repositories.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
actual, err := ValidateImage(data, contentType)
|
||||
if err = ctx.Err(); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
actual, err := ValidateImageReader(file, contentType)
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
if err = s.objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if err = s.metadata.Create(ctx, a); err != nil {
|
||||
// A connection error can hide a successful autocommit. Delete only after
|
||||
// a definite SQL rejection; otherwise preserve bytes for later reconciliation.
|
||||
var rejected *pgconn.PgError
|
||||
if errors.As(err, &rejected) {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if cleanupErr := s.objects.Delete(cleanup, a.ObjectKey); cleanupErr != nil {
|
||||
log.Printf("attachment compensation failed for %s", a.ID)
|
||||
}
|
||||
} else {
|
||||
log.Printf("attachment metadata outcome uncertain for %s; preserving S3 object", a.ID)
|
||||
}
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
if err = s.metadata.ReserveUpload(ctx, a, grace); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
err = s.metadata.PublishUpload(ctx, a, func(ctx context.Context) error {
|
||||
return s.objects.Put(ctx, a.ObjectKey, file, a.SizeBytes, a.ContentType)
|
||||
})
|
||||
// On any uncertainty leave the durable reservation to the cleanup worker.
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
return a, nil
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestAttachmentCleanupGraceLocksProtectionAndRetry(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
data := uploadPNG(t)
|
||||
makeAttempt := func(age bool, ready bool) repositories.Attachment {
|
||||
id := uuid.NewString()
|
||||
now := time.Now().UTC()
|
||||
a := repositories.Attachment{ID: id, ObjectKey: "originals/" + id, ChatID: chat, OwnerID: user, Filename: "cleanup.png", ContentType: "image/png", SizeBytes: int64(len(data)), SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", CreatedAt: now, UpdatedAt: now}
|
||||
if err := objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), a.ObjectKey) })
|
||||
if err := store.ReserveUpload(ctx, a, 600*time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if age {
|
||||
if _, err := f.db.Exec(ctx, "UPDATE upload_attempts SET cleanup_after=clock_timestamp()-interval '1 second' WHERE id=$1", id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if ready {
|
||||
if err := store.Create(ctx, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
fresh := makeAttempt(false, false)
|
||||
expired := makeAttempt(true, false)
|
||||
ready := makeAttempt(true, true)
|
||||
locked := makeAttempt(true, false)
|
||||
tx, err := f.db.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "SELECT id FROM upload_attempts WHERE id=$1 FOR UPDATE", locked.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dry, err := store.CleanupUploads(ctx, true, objects.Delete)
|
||||
if err != nil || dry.Deleted != 0 || dry.Candidates != 3 || dry.Protected != 1 {
|
||||
t.Fatalf("dry run: %+v %v", dry, err)
|
||||
}
|
||||
result, err := store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 || result.Protected != 1 || result.Skipped != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", result, err)
|
||||
}
|
||||
if content, err := objects.Get(ctx, expired.ObjectKey); err == nil {
|
||||
content.Close()
|
||||
t.Fatal("expired object not removed")
|
||||
}
|
||||
for _, a := range []repositories.Attachment{fresh, ready, locked} {
|
||||
content, err := objects.Get(ctx, a.ObjectKey)
|
||||
if err != nil {
|
||||
t.Fatalf("protected object removed: %v", err)
|
||||
}
|
||||
content.Close()
|
||||
}
|
||||
tx.Rollback(ctx)
|
||||
failure, err := store.CleanupUploads(ctx, false, func(context.Context, string) error { return errors.New("injected S3 DELETE failure") })
|
||||
if err == nil || failure.Failed != 1 {
|
||||
t.Fatalf("DELETE failure: %+v %v", failure, err)
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts WHERE id=$1", locked.ID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Fatal("DELETE failure lost journal")
|
||||
}
|
||||
result, err = store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 {
|
||||
t.Fatalf("retry: %+v %v", result, err)
|
||||
}
|
||||
result, err = store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Candidates != 0 {
|
||||
t.Fatalf("repeat not idempotent: %+v %v", result, err)
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err = store.CleanupUploads(cancelled, false, objects.Delete); err == nil {
|
||||
t.Fatal("cancelled DB operation succeeded")
|
||||
}
|
||||
f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts WHERE id=$1", fresh.ID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Fatal("DB failure lost fresh reservation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentCleanupInvalidKeyIsNeverDeleted(t *testing.T) {
|
||||
f, store, _, _, _ := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := f.db.Exec(ctx, "INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()-interval '1 second')", uuid.NewString(), "do-not-delete/anything"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
called := false
|
||||
result, err := store.CleanupUploads(ctx, false, func(context.Context, string) error { called = true; return nil })
|
||||
if err == nil || called || result.Failed != 1 {
|
||||
t.Fatalf("unsafe key: %+v %v delete=%v", result, err, called)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func attachmentRouter(f *testFixture, objects *repositories.ObjectStore) http.Handler {
|
||||
users := services.NewUserService(f.users)
|
||||
return handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(f.db), f.sessionStore), users, f.sessions, services.NewChatService(f.chats), services.NewMessageService(f.messages), services.NewAttachmentService(repositories.NewAttachmentStore(f.db), objects))
|
||||
}
|
||||
func attachmentCall(t *testing.T, f *testFixture, router http.Handler, method, path, user, mime string, body []byte, status int) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, bytes.NewReader(body))
|
||||
if mime != "" {
|
||||
r.Header.Set("Content-Type", mime)
|
||||
}
|
||||
if method == "POST" && strings.HasSuffix(path, "/messages") {
|
||||
r.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
if user != "" {
|
||||
authorizeTestRequest(t, f, r, user)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != status {
|
||||
t.Fatalf("%s %s: expected %d, got %d: %s", method, path, status, w.Code, w.Body.String())
|
||||
}
|
||||
if status >= 400 {
|
||||
var error struct {
|
||||
Error struct {
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &error); err != nil || error.Error.RequestID != w.Header().Get("X-Request-Id") {
|
||||
t.Fatal("invalid error envelope")
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
func TestAttachmentValidationHTTP(t *testing.T) {
|
||||
f, _, objects, user, chat := uploadFixture(t)
|
||||
router := attachmentRouter(f, objects)
|
||||
path := "/api/v1/chats/" + chat + "/attachments?filename=photo.png"
|
||||
png := uploadPNG(t)
|
||||
for _, sample := range []struct {
|
||||
body []byte
|
||||
mime string
|
||||
status int
|
||||
}{{bytes.Repeat([]byte("x"), 10485761), "image/png", 413}, {png[:40], "image/png", 415}, {png, "image/jpeg", 415}, {png, "text/plain", 415}} {
|
||||
attachmentCall(t, f, router, "POST", path, user, sample.mime, sample.body, sample.status)
|
||||
}
|
||||
huge := append([]byte(nil), png...)
|
||||
binary.BigEndian.PutUint32(huge[16:20], 10001)
|
||||
binary.BigEndian.PutUint32(huge[20:24], 4000)
|
||||
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
|
||||
attachmentCall(t, f, router, "POST", path, user, "image/png", huge, 413)
|
||||
for _, name := range []string{"", " ", "../file.png", `a\b.png`, "a\x00.png", "a\n.png", strings.Repeat("x", 256)} {
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/attachments?"+url.Values{"filename": {name}}.Encode(), user, "image/png", png, 400)
|
||||
}
|
||||
// Exercise the real HTTP chunked path without Content-Length.
|
||||
server := httptest.NewServer(router)
|
||||
defer server.Close()
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, writer := io.Pipe()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer writer.Close()
|
||||
io.Copy(writer, bytes.NewReader(bytes.Repeat([]byte("x"), 10485761)))
|
||||
}()
|
||||
request, err := http.NewRequest("POST", server.URL+path, reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("Content-Type", "image/png")
|
||||
response, err := server.Client().Do(request)
|
||||
if err != nil {
|
||||
reader.Close()
|
||||
<-done
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
reader.Close()
|
||||
<-done
|
||||
if response.StatusCode != 413 {
|
||||
t.Fatalf("chunked limit: %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentAccessHTTP(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
router := attachmentRouter(f, objects)
|
||||
eve, _ := createTestUser(t, f.users, "eve", "Eve")
|
||||
other := createTestChat(t, f.chats, "Other", []string{user})
|
||||
a, err := services.NewAttachmentService(store, objects).Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), a.ObjectKey) })
|
||||
for _, suffix := range []string{"", "/content"} {
|
||||
path := "/api/v1/attachments/" + a.ID + suffix
|
||||
attachmentCall(t, f, router, "GET", path, eve.ID, "", nil, 404)
|
||||
attachmentCall(t, f, router, "GET", path, "", "", nil, 401)
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/attachments?filename=photo.png", eve.ID, "image/png", uploadPNG(t), 404)
|
||||
for _, target := range []string{uuid.NewString(), a.ID} {
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+other.ID+"/messages", user, "application/json", []byte(`{"text":"","attachment_ids":["`+target+`"]}`), 404)
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/messages", user, "application/json", []byte(`{"text":"","attachment_ids":["`+a.ID+`","`+a.ID+`"]}`), 400)
|
||||
}
|
||||
|
||||
func TestUploadRecoveryHTTPDisconnect(t *testing.T) {
|
||||
f, _, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
completed := make(chan struct{})
|
||||
router := attachmentRouter(f, objects)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer close(completed); router.ServeHTTP(w, r) }))
|
||||
defer server.Close()
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := strings.TrimPrefix(server.URL, "http://")
|
||||
connection, err := net.Dial("tcp", address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := "POST /api/v1/chats/" + chat + "/attachments?filename=aborted.png HTTP/1.1\r\nHost: " + address + "\r\nAuthorization: Bearer " + token + "\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\n\r\npartial"
|
||||
if _, err = io.WriteString(connection, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connection.Close()
|
||||
select {
|
||||
case <-completed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("disconnected upload did not stop")
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(context.Background(), "SELECT count(*) FROM upload_attempts").Scan(&count)
|
||||
if count != 0 {
|
||||
t.Fatal("incomplete HTTP body reserved an object")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) > 0 {
|
||||
t.Fatalf("temporary paths remain: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
func s3Client(t *testing.T, root bool, anonymous bool) *minio.Client {
|
||||
t.Helper()
|
||||
if os.Getenv("S3_ENDPOINT") == "" {
|
||||
t.Skip("S3 integration: run make test-backend")
|
||||
}
|
||||
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read := func(name string) string {
|
||||
data, err := os.ReadFile(os.Getenv(name))
|
||||
if err != nil {
|
||||
t.Fatal("S3 credential file not mounted")
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
access, secret := "", ""
|
||||
if !anonymous {
|
||||
if root {
|
||||
access = read("S3_ROOT_ACCESS_KEY_ID_FILE")
|
||||
secret = read("S3_ROOT_SECRET_ACCESS_KEY_FILE")
|
||||
} else {
|
||||
access = read("S3_ACCESS_KEY_ID_FILE")
|
||||
secret = read("S3_SECRET_ACCESS_KEY_FILE")
|
||||
}
|
||||
}
|
||||
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
func denied(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if err == nil || minio.ToErrorResponse(err).StatusCode != 403 {
|
||||
t.Fatalf("expected S3 HTTP 403, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3PermissionsAndBootstrap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
app := s3Client(t, false, false)
|
||||
root := s3Client(t, true, false)
|
||||
anon := s3Client(t, false, true)
|
||||
bucket := os.Getenv("S3_BUCKET")
|
||||
key := "originals/" + uuid.NewString()
|
||||
data := []byte("permission fixture")
|
||||
t.Cleanup(func() { root.RemoveObject(context.Background(), bucket, key, minio.RemoveObjectOptions{}) })
|
||||
if _, err := app.PutObject(ctx, bucket, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := repositories.BootstrapS3(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
content, err := app.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, err := io.ReadAll(content)
|
||||
content.Close()
|
||||
if err != nil || !bytes.Equal(actual, data) {
|
||||
t.Fatalf("bootstrap changed existing object: %v", err)
|
||||
}
|
||||
object, err := anon.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = object.Stat()
|
||||
object.Close()
|
||||
denied(t, err)
|
||||
listing, ok := <-anon.ListObjects(ctx, bucket, minio.ListObjectsOptions{})
|
||||
if !ok {
|
||||
t.Fatal("anonymous list did not return AccessDenied")
|
||||
}
|
||||
denied(t, listing.Err)
|
||||
forbidden := "forbidden/" + uuid.NewString()
|
||||
t.Cleanup(func() { root.RemoveObject(context.Background(), bucket, forbidden, minio.RemoveObjectOptions{}) })
|
||||
_, err = app.PutObject(ctx, bucket, forbidden, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{})
|
||||
denied(t, err)
|
||||
if _, err = root.PutObject(ctx, bucket, forbidden, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside, err := app.GetObject(ctx, bucket, forbidden, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = outside.Stat()
|
||||
outside.Close()
|
||||
denied(t, err)
|
||||
denied(t, app.RemoveObject(ctx, bucket, forbidden, minio.RemoveObjectOptions{}))
|
||||
other := "upload-permissions-" + uuid.NewString()
|
||||
if err = root.MakeBucket(ctx, other, minio.MakeBucketOptions{Region: os.Getenv("S3_REGION")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
root.RemoveObject(context.Background(), other, key, minio.RemoveObjectOptions{})
|
||||
root.RemoveBucket(context.Background(), other)
|
||||
})
|
||||
_, err = app.PutObject(ctx, other, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{})
|
||||
denied(t, err)
|
||||
denied(t, app.MakeBucket(ctx, "forbidden-"+uuid.NewString(), minio.MakeBucketOptions{}))
|
||||
denied(t, app.SetBucketPolicy(ctx, bucket, ""))
|
||||
if err = app.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Admin APIs have a separate JSON error type; reject exactly AccessDenied.
|
||||
endpoint, _ := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
access, _ := os.ReadFile(os.Getenv("S3_ACCESS_KEY_ID_FILE"))
|
||||
secret, _ := os.ReadFile(os.Getenv("S3_SECRET_ACCESS_KEY_FILE"))
|
||||
admin, err := madmin.New(endpoint.Host, strings.TrimSpace(string(access)), strings.TrimSpace(string(secret)), endpoint.Scheme == "https")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = admin.ListUsers(ctx)
|
||||
if err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
t.Fatalf("API credentials permit admin access or wrong error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = schema
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -92,6 +93,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000005_upload_attempts.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type uploadFault struct {
|
||||
*repositories.ObjectStore
|
||||
afterPut func() error
|
||||
}
|
||||
|
||||
func (s uploadFault) Put(ctx context.Context, key string, reader io.Reader, size int64, mime string) error {
|
||||
if err := s.ObjectStore.Put(ctx, key, reader, size, mime); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.afterPut()
|
||||
}
|
||||
|
||||
func uploadObjects(t *testing.T) *repositories.ObjectStore {
|
||||
t.Helper()
|
||||
if os.Getenv("S3_ENDPOINT") == "" {
|
||||
t.Skip("S3 integration: run make test-backend")
|
||||
}
|
||||
store, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store
|
||||
}
|
||||
func uploadPNG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var buffer bytes.Buffer
|
||||
if err := png.Encode(&buffer, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
func uploadFixture(t *testing.T) (*testFixture, *repositories.AttachmentStore, *repositories.ObjectStore, string, string) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
chat := createTestChat(t, f.chats, "Upload recovery", []string{user.ID})
|
||||
return f, repositories.NewAttachmentStore(f.db), uploadObjects(t), user.ID, chat.ID
|
||||
}
|
||||
func ageAndClean(t *testing.T, f *testFixture, store *repositories.AttachmentStore, objects *repositories.ObjectStore) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var key string
|
||||
if err := f.db.QueryRow(ctx, "SELECT object_key FROM upload_attempts").Scan(&key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), key) })
|
||||
if _, err := f.db.Exec(ctx, "UPDATE upload_attempts SET cleanup_after=clock_timestamp()-interval '1 second'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", result, err)
|
||||
}
|
||||
if content, err := objects.Get(ctx, key); err == nil {
|
||||
content.Close()
|
||||
t.Fatal("orphan still exists")
|
||||
}
|
||||
var count int
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("journal: %d %v", count, err)
|
||||
}
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM attachments").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("unexpected metadata: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadRecoveryAfterPutFailure(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, func() error { return errors.New("injected PUT result loss") }})
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected failure")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
func TestUploadRecoveryMetadataRejection(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
if _, err := f.db.Exec(context.Background(), `ALTER TABLE attachments ADD CONSTRAINT reject_fixture CHECK(filename <> 'reject.png')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := services.NewAttachmentService(store, objects)
|
||||
if _, err := service.Upload(context.Background(), user, chat, "reject.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected metadata rejection")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
func TestUploadRecoveryDatabaseConnectionLoss(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
// Kill only this fixture's idle upload transaction, after its S3 PUT.
|
||||
fault := func() error {
|
||||
_, err := f.db.Exec(context.Background(), `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name=$1 AND state='idle in transaction' AND pid<>pg_backend_pid()`, f.db.Config().ConnConfig.RuntimeParams["application_name"])
|
||||
return err
|
||||
}
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, fault})
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected connection loss")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
|
||||
func TestUploadRecoveryProcessExit(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
child := exec.Command(os.Args[0], "-test.run=^TestUploadCrashHelper$")
|
||||
child.Env = append(os.Environ(), "UPLOAD_CRASH_HELPER=1", "UPLOAD_TEST_DATABASE="+f.db.Config().ConnString(), "UPLOAD_TEST_SCHEMA="+f.db.Config().ConnConfig.RuntimeParams["search_path"], "UPLOAD_TEST_USER="+user, "UPLOAD_TEST_CHAT="+chat)
|
||||
output, err := child.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 23 {
|
||||
t.Fatalf("helper did not exit after PUT: %v %s", err, output)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("temporary files left after exit: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
func TestUploadCrashHelper(t *testing.T) {
|
||||
if os.Getenv("UPLOAD_CRASH_HELPER") != "1" {
|
||||
return
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(os.Getenv("UPLOAD_TEST_DATABASE"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
db, err := pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects := uploadObjects(t)
|
||||
service := services.NewAttachmentService(repositories.NewAttachmentStore(db), uploadFault{objects, func() error { os.Exit(23); return nil }})
|
||||
_, err = service.Upload(context.Background(), os.Getenv("UPLOAD_TEST_USER"), os.Getenv("UPLOAD_TEST_CHAT"), "crash.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
t.Fatalf("helper failed before exit: %v", err)
|
||||
}
|
||||
|
||||
type interruptedReader struct{ first bool }
|
||||
|
||||
func (r *interruptedReader) Read(p []byte) (int, error) {
|
||||
if !r.first {
|
||||
r.first = true
|
||||
return copy(p, []byte("partial PNG")), nil
|
||||
}
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
func TestUploadRecoveryInterruptedBody(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
service := services.NewAttachmentService(store, objects)
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", &interruptedReader{}); !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Fatalf("body interruption: %v", err)
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(context.Background(), "SELECT count(*) FROM upload_attempts").Scan(&count)
|
||||
if count != 0 {
|
||||
t.Fatal("reservation before complete body")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("temporary paths left: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
func TestUploadRecoveryWaitingCancellation(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, func() error { close(entered); <-release; return errors.New("test stop") }})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
service.Upload(context.Background(), user, chat, "first.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("first upload did not reach PUT")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := service.Upload(ctx, user, chat, "second.png", "image/png", strings.NewReader("unused"))
|
||||
close(release)
|
||||
<-done
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("waiting upload ignored cancellation: %v", err)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
+28
-5
@@ -6,9 +6,10 @@ require (
|
||||
github.com/golang-migrate/migrate/v4 v4.17.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.5.5
|
||||
github.com/minio/madmin-go/v3 v3.0.70
|
||||
github.com/minio/minio-go/v7 v7.0.76
|
||||
github.com/redis/go-redis/v9 v9.17.3
|
||||
golang.org/x/crypto v0.26.0
|
||||
golang.org/x/crypto v0.27.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -16,7 +17,10 @@ require (
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect
|
||||
@@ -25,11 +29,30 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/klauspost/compress v1.17.9 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/philhofer/fwd v1.1.3-0.20240612014219-fbbf4953d986 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.59.1 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/prometheus/prom2json v1.4.0 // indirect
|
||||
github.com/prometheus/prometheus v0.54.1 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
golang.org/x/net v0.28.0 // indirect
|
||||
github.com/safchain/ethtool v0.4.1 // indirect
|
||||
github.com/secure-io/sio-go v0.3.1 // indirect
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/tinylib/msgp v1.2.1 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.14 // indirect
|
||||
github.com/tklauser/numcpus v0.8.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/net v0.29.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.24.0 // indirect
|
||||
golang.org/x/text v0.17.0 // indirect
|
||||
golang.org/x/sys v0.25.0 // indirect
|
||||
golang.org/x/text v0.18.0 // indirect
|
||||
google.golang.org/protobuf v1.34.2 // indirect
|
||||
)
|
||||
|
||||
+102
-21
@@ -9,30 +9,46 @@ github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dhui/dktest v0.4.1 h1:/w+IWuDXVymg3IrRJCHHOkMK10m9aNVMOyD0X12YVTg=
|
||||
github.com/dhui/dktest v0.4.1/go.mod h1:DdOqcUpL7vgyP4GlF3X3w7HbSlz8cEQzwewPveYEQbA=
|
||||
github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
|
||||
github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||
github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0=
|
||||
github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=
|
||||
github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.0.3+incompatible h1:aBGI9TeQ4MPlhquTQKq9XbK79rKFVwXNUAYz9aXyEBE=
|
||||
github.com/docker/docker v27.0.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
|
||||
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4=
|
||||
github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
@@ -57,48 +73,113 @@ github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS
|
||||
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 h1:7UMa6KCCMjZEMDtTVdcGu0B1GmmC7QJKiCCjyTAWQy0=
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/minio/madmin-go/v3 v3.0.70 h1:zrFCXLcV6PR74JC0yytK4Dk2qsaCV8kXQoPTvcusR2k=
|
||||
github.com/minio/madmin-go/v3 v3.0.70/go.mod h1:TOTc96ZkMknNhl+ReO/V68bQfgRGfH+8iy7YaDzHdXA=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.76 h1:9nxHH2XDai61cT/EFhyIw/wW4vJfpPNvl7lSFpRt+Ng=
|
||||
github.com/minio/minio-go/v7 v7.0.76/go.mod h1:AVM3IUN6WwKzmwBxVdjzhH8xq+f57JSbbvzqvUzR6eg=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM=
|
||||
github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
|
||||
github.com/philhofer/fwd v1.1.3-0.20240612014219-fbbf4953d986 h1:jYi87L8j62qkXzaYHAQAhEapgukhenIMZRBKTNRLHJ4=
|
||||
github.com/philhofer/fwd v1.1.3-0.20240612014219-fbbf4953d986/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
|
||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
|
||||
github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJoX0=
|
||||
github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0=
|
||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||
github.com/prometheus/prom2json v1.4.0 h1:2AEOsd1ebqql/p9u0IWgCpUAteAAf9Lnf/SVyieqer4=
|
||||
github.com/prometheus/prom2json v1.4.0/go.mod h1:DmcIMPspQD/fMyFCYti5qJJbuEnqDh3DGoooO0sgr4w=
|
||||
github.com/prometheus/prometheus v0.54.1 h1:vKuwQNjnYN2/mDoWfHXDhAsz/68q/dQDb+YbcEqU7MQ=
|
||||
github.com/prometheus/prometheus v0.54.1/go.mod h1:xlLByHhk2g3ycakQGrMaU8K7OySZx98BzeCR99991NY=
|
||||
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/safchain/ethtool v0.4.1 h1:S6mEleTADqgynileXoiapt/nKnatyR6bmIHoF+h2ADo=
|
||||
github.com/safchain/ethtool v0.4.1/go.mod h1:XLLnZmy4OCRTkksP/UiMjij96YmIsBfmBQcs7H6tA48=
|
||||
github.com/secure-io/sio-go v0.3.1 h1:dNvY9awjabXTYGsTF1PiCySl9Ltofk9GA3VdWlo7rRc=
|
||||
github.com/secure-io/sio-go v0.3.1/go.mod h1:+xbkjDzPjwh4Axd07pRKSNriS9SCiYksWnZqdnfpQxs=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
|
||||
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
|
||||
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
github.com/tinylib/msgp v1.2.1 h1:6ypy2qcCznxpP4hpORzhtXyTqrBs7cfM9MCCWY8zsmU=
|
||||
github.com/tinylib/msgp v1.2.1/go.mod h1:2vIGs3lcUo8izAATNobrCHevYZC/LMsJtw4JPiYPHro=
|
||||
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
|
||||
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
|
||||
github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY=
|
||||
github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 h1:4K4tsIXefpVJtvA/8srF4V4y0akAoPHkIslgAkjixJA=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0/go.mod h1:jjdQuTGVsXV4vSs+CJ2qYDeDPf9yIJV23qlIzBm73Vg=
|
||||
go.opentelemetry.io/otel v1.28.0 h1:/SqNcYk+idO0CxKEUOtKQClMK/MimZihKYMruSMViUo=
|
||||
go.opentelemetry.io/otel v1.28.0/go.mod h1:q68ijF8Fc8CnMHKyzqL6akLO46ePnjkgfIMIjUIX9z4=
|
||||
go.opentelemetry.io/otel/metric v1.28.0 h1:f0HGvSl1KRAU1DLgLGFjrwVyismPlnuU6JD6bOeuA5Q=
|
||||
go.opentelemetry.io/otel/metric v1.28.0/go.mod h1:Fb1eVBFZmLVTMb6PPohq3TO9IIhUisDsbJoL/+uQW4s=
|
||||
go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+lkx9g=
|
||||
go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
|
||||
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
|
||||
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
||||
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
|
||||
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
|
||||
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
Reference in New Issue
Block a user