Implement durable S3 attachments and reconciliation
This commit is contained in:
Executable
+178
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure bounded API memory during concurrent, valid attachment uploads.
|
||||
|
||||
The script uses only the standard library and Docker CLI. It creates isolated
|
||||
test data, submits N uploads concurrently, samples both API containers' memory,
|
||||
and prints a token-free JSON summary suitable for evidence.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
MEMORY_VALUE = re.compile(r"([0-9.]+)\s*([KMGT]?i?B)")
|
||||
UNIT_BYTES = {"B": 1, "KB": 1000, "MB": 1000**2, "GB": 1000**3,
|
||||
"TB": 1000**4, "KiB": 1024, "MiB": 1024**2,
|
||||
"GiB": 1024**3, "TiB": 1024**4}
|
||||
|
||||
|
||||
def request(method: str, base_url: str, path: str, *, body: dict[str, Any] | None = None,
|
||||
raw: bytes | None = None, headers: dict[str, str] | None = None,
|
||||
timeout: float = 90) -> tuple[int, bytes]:
|
||||
data = raw
|
||||
request_headers = {"Accept": "application/json"}
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
request_headers.update(headers or {})
|
||||
prepared = urllib.request.Request(base_url + path, data=data, headers=request_headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(prepared, timeout=timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
def require_json(status: int, data: bytes, expected: int) -> dict[str, Any]:
|
||||
if status != expected:
|
||||
raise RuntimeError("expected HTTP %s, received %s: %s" % (expected, status, data[:300]))
|
||||
return json.loads(data)
|
||||
|
||||
|
||||
def docker_api_containers(env_file: str) -> list[str]:
|
||||
completed = subprocess.run(
|
||||
["docker", "compose", "--env-file", env_file, "ps", "-q", "api-1", "api-2"],
|
||||
cwd=ROOT, check=True, text=True, capture_output=True,
|
||||
)
|
||||
containers = completed.stdout.split()
|
||||
if len(containers) != 2:
|
||||
raise RuntimeError("both API replicas must be running before the experiment")
|
||||
return containers
|
||||
|
||||
|
||||
def memory_bytes(containers: list[str]) -> int:
|
||||
completed = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *containers],
|
||||
check=True, text=True, capture_output=True,
|
||||
)
|
||||
total = 0
|
||||
for line in completed.stdout.splitlines():
|
||||
match = MEMORY_VALUE.search(line)
|
||||
if match is None:
|
||||
raise RuntimeError("cannot parse docker memory output: " + line)
|
||||
total += int(float(match.group(1)) * UNIT_BYTES[match.group(2)])
|
||||
return total
|
||||
|
||||
|
||||
def percentile(values: list[float], fraction: float) -> float:
|
||||
values = sorted(values)
|
||||
return values[min(len(values) - 1, max(0, round((len(values) - 1) * fraction)))]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8083")
|
||||
parser.add_argument("--concurrency", type=int, default=10)
|
||||
parser.add_argument("--payload-mib", type=int, default=8)
|
||||
parser.add_argument("--env-file", default=".env")
|
||||
parser.add_argument("--evidence", type=Path)
|
||||
args = parser.parse_args()
|
||||
if not 10 <= args.concurrency <= 40:
|
||||
raise SystemExit("concurrency must be 10..40")
|
||||
if not 2 <= args.payload_mib <= 10:
|
||||
raise SystemExit("payload-mib must be 2..10")
|
||||
base_url = args.base_url.rstrip("/")
|
||||
payload = PNG + b"\0" * (args.payload_mib * 1024 * 1024 - len(PNG))
|
||||
registration = {
|
||||
"username": "load_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Attachment load test",
|
||||
"password": "Load-" + uuid.uuid4().hex,
|
||||
}
|
||||
user = require_json(*request("POST", base_url, "/api/v1/users", body=registration), 201)
|
||||
basic = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
||||
session = require_json(*request("POST", base_url, "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + basic}), 201)
|
||||
token = session["token"]
|
||||
chat = require_json(*request("POST", base_url, "/api/v1/chats",
|
||||
body={"title": "Attachment memory experiment", "member_ids": [user["id"]]},
|
||||
headers={"Authorization": "Bearer " + token}), 201)
|
||||
path = "/api/v1/chats/%s/attachments?filename=memory.png" % chat["id"]
|
||||
containers = docker_api_containers(args.env_file)
|
||||
baseline = memory_bytes(containers)
|
||||
samples: list[int] = []
|
||||
monitor_error: list[str] = []
|
||||
stop = threading.Event()
|
||||
|
||||
def monitor() -> None:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
samples.append(memory_bytes(containers))
|
||||
except (OSError, subprocess.SubprocessError, RuntimeError) as exc:
|
||||
monitor_error.append(type(exc).__name__)
|
||||
return
|
||||
stop.wait(0.1)
|
||||
|
||||
thread = threading.Thread(target=monitor, daemon=True)
|
||||
thread.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
def upload(_: int) -> tuple[int, float]:
|
||||
started = time.monotonic()
|
||||
status, _ = request("POST", base_url, path, raw=payload, headers={
|
||||
"Authorization": "Bearer " + token, "Content-Type": "image/png",
|
||||
})
|
||||
return status, time.monotonic() - started
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
|
||||
results = list(executor.map(upload, range(args.concurrency)))
|
||||
elapsed = time.monotonic() - started
|
||||
stop.set()
|
||||
thread.join(timeout=3)
|
||||
statuses = [status for status, _ in results]
|
||||
durations_ms = [duration * 1000 for _, duration in results]
|
||||
if monitor_error:
|
||||
raise RuntimeError("memory sampling failed: " + monitor_error[0])
|
||||
if not samples:
|
||||
raise RuntimeError("memory sampling returned no samples")
|
||||
summary = {
|
||||
"concurrency": args.concurrency,
|
||||
"payload_bytes_each": len(payload),
|
||||
"successful_uploads": statuses.count(201),
|
||||
"failed_uploads": len(statuses) - statuses.count(201),
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_rps": round(statuses.count(201) / elapsed, 3),
|
||||
"latency_ms": {"p50": round(percentile(durations_ms, .50), 1),
|
||||
"p95": round(percentile(durations_ms, .95), 1),
|
||||
"p99": round(percentile(durations_ms, .99), 1)},
|
||||
"api_memory_bytes": {"baseline_before_test": baseline, "peak_sample": max([baseline, *samples]),
|
||||
"growth": max([baseline, *samples]) - baseline, "samples": len(samples)},
|
||||
"memory_method": "sum of docker stats for api-1 and api-2; baseline before requests, then repeat after a 100 ms wait",
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, sort_keys=True)
|
||||
print(text)
|
||||
if args.evidence is not None:
|
||||
args.evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.evidence.write_text(text + "\n", encoding="utf-8")
|
||||
if summary["failed_uploads"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/bin/sh
|
||||
# Generate the local, synthetic stand's secrets and .env.
|
||||
# Values are written to ./secrets (git-ignored, mode 0600) and never printed.
|
||||
# Re-running is safe: existing files are kept unless FORCE=1.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
PYTHON="${PYTHON:-python}"
|
||||
SECRETS_DIR="${SECRETS_DIR:-secrets}"
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env
|
||||
printf '%s\n' "created .env from .env.example"
|
||||
fi
|
||||
|
||||
mkdir -p "$SECRETS_DIR"
|
||||
chmod 700 "$SECRETS_DIR" 2>/dev/null || true
|
||||
|
||||
umask 077
|
||||
|
||||
random_password() {
|
||||
"$PYTHON" -c 'import secrets; print(secrets.token_hex(24))'
|
||||
}
|
||||
|
||||
write_if_missing() {
|
||||
path="$SECRETS_DIR/$1"
|
||||
if [ -f "$path" ] && [ "${FORCE:-0}" != "1" ]; then
|
||||
return 0
|
||||
fi
|
||||
printf '%s' "$2" > "$path"
|
||||
chmod 600 "$path" 2>/dev/null || true
|
||||
}
|
||||
|
||||
postgres_password="$(random_password)"
|
||||
valkey_password="$(random_password)"
|
||||
s3_access_key_id="messenger-api"
|
||||
s3_secret_access_key="$(random_password)"
|
||||
s3_bootstrap_access_key_id="messenger-bootstrap"
|
||||
s3_bootstrap_secret_access_key="$(random_password)"
|
||||
|
||||
write_if_missing postgres_password "$postgres_password"
|
||||
write_if_missing valkey_password "$valkey_password"
|
||||
write_if_missing database_url "postgresql://messenger:${postgres_password}@postgres:5432/messenger"
|
||||
write_if_missing cache_url "redis://:${valkey_password}@valkey:6379/0"
|
||||
write_if_missing s3_access_key_id "$s3_access_key_id"
|
||||
write_if_missing s3_secret_access_key "$s3_secret_access_key"
|
||||
write_if_missing s3_bootstrap_access_key_id "$s3_bootstrap_access_key_id"
|
||||
write_if_missing s3_bootstrap_secret_access_key "$s3_bootstrap_secret_access_key"
|
||||
|
||||
# SeaweedFS consumes an S3 identity policy file. API has only data-plane rights;
|
||||
# bucket creation uses a separate identity unavailable to API processes.
|
||||
if [ ! -f "$SECRETS_DIR/s3.json" ] || [ "${FORCE:-0}" = "1" ]; then
|
||||
cat >"$SECRETS_DIR/s3.json" <<EOF
|
||||
{"identities":[{"name":"messenger-api","credentials":[{"accessKey":"$s3_access_key_id","secretKey":"$s3_secret_access_key"}],"actions":["Read","Write","List","Tagging"]},{"name":"messenger-bootstrap","credentials":[{"accessKey":"$s3_bootstrap_access_key_id","secretKey":"$s3_bootstrap_secret_access_key"}],"actions":["Read","Write","List","Tagging","Admin"]}]}
|
||||
EOF
|
||||
chmod 600 "$SECRETS_DIR/s3.json" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
printf '%s\n' "wrote secrets to $SECRETS_DIR: postgres, valkey, restricted S3 API and bootstrap credentials"
|
||||
printf '%s\n' "next: docker compose --env-file .env up -d --build"
|
||||
@@ -8,8 +8,8 @@ import re
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
@@ -41,11 +41,11 @@ def main():
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
json.loads(file.read_text(encoding='utf-8'))
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file "${COMPOSE_ENV_FILE:-.env}" exec -T api-1 python -m src.reconcile "$@"
|
||||
Executable
+125
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject and restore a missing S3 object to prove reconciler safety.
|
||||
|
||||
Creates an isolated attachment through the public API, removes only its
|
||||
server-generated S3 key from inside the private network, verifies detection and
|
||||
non-destructive ``--apply``, restores the exact bytes, and verifies a clean scan.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
|
||||
def request(method: str, base_url: str, path: str, *, body: dict[str, Any] | None = None,
|
||||
raw: bytes | None = None, headers: dict[str, str] | None = None) -> tuple[int, bytes]:
|
||||
data = raw if body is None else json.dumps(body).encode("utf-8")
|
||||
request_headers = {"Accept": "application/json"}
|
||||
if body is not None:
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
request_headers.update(headers or {})
|
||||
prepared = urllib.request.Request(base_url + path, data=data, headers=request_headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(prepared, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
def require_json(response: tuple[int, bytes], expected: int) -> dict[str, Any]:
|
||||
status, data = response
|
||||
if status != expected:
|
||||
raise RuntimeError("expected HTTP %s, received %s: %s" % (expected, status, data[:300]))
|
||||
return json.loads(data)
|
||||
|
||||
|
||||
def reconcile(env_file: str, *args: str) -> dict[str, Any]:
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", env_file, "exec", "-T", "api-1", "python", "-m", "src.reconcile", *args],
|
||||
cwd=ROOT, check=True, text=True, capture_output=True,
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def s3_command(env_file: str, source: str) -> None:
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", env_file, "exec", "-T", "api-1", "python", "-c", source],
|
||||
cwd=ROOT, check=True, text=True, capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8083")
|
||||
parser.add_argument("--env-file", default=".env")
|
||||
parser.add_argument("--evidence", type=Path)
|
||||
args = parser.parse_args()
|
||||
base_url = args.base_url.rstrip("/")
|
||||
registration = {"username": "missing_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Missing S3 experiment", "password": "Missing-" + uuid.uuid4().hex}
|
||||
user = require_json(request("POST", base_url, "/api/v1/users", body=registration), 201)
|
||||
basic = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
||||
session = require_json(request("POST", base_url, "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + basic}), 201)
|
||||
token = session["token"]
|
||||
chat = require_json(request("POST", base_url, "/api/v1/chats",
|
||||
body={"title": "Missing S3 experiment", "member_ids": [user["id"]]},
|
||||
headers={"Authorization": "Bearer " + token}), 201)
|
||||
attachment = require_json(request("POST", base_url,
|
||||
"/api/v1/chats/%s/attachments?filename=missing.png" % chat["id"], raw=PNG,
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"}), 201)
|
||||
key = "attachments/" + attachment["id"]
|
||||
delete_code = "from src.config import load_settings; from src.object_store import ObjectStore; ObjectStore(load_settings()).delete(%r)" % key
|
||||
s3_command(args.env_file, delete_code)
|
||||
unavailable_status, unavailable_body = request("GET", base_url, "/api/v1/attachments/%s/content" % attachment["id"],
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
missing_dry_run = reconcile(args.env_file, "--grace-seconds", "60")
|
||||
missing_apply = reconcile(args.env_file, "--apply", "--grace-seconds", "60")
|
||||
# Do not put image bytes on a Windows command line: it is capped at 32 KiB.
|
||||
# docker compose cp crosses the private container boundary without exposing S3.
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", args.env_file, "cp",
|
||||
str(ROOT / "tests" / "fixtures" / "sample.png"), "api-1:/tmp/reconcile-restore.png"],
|
||||
cwd=ROOT, check=True, text=True, capture_output=True,
|
||||
)
|
||||
restore_code = (
|
||||
"from src.config import load_settings; from src.object_store import ObjectStore; "
|
||||
"source=open('/tmp/reconcile-restore.png','rb'); "
|
||||
"ObjectStore(load_settings()).put(%r,source,%s,'image/png'); source.close()"
|
||||
% (key, len(PNG))
|
||||
)
|
||||
s3_command(args.env_file, restore_code)
|
||||
final_dry_run = reconcile(args.env_file, "--grace-seconds", "60")
|
||||
restored_status, restored_bytes = request("GET", base_url, "/api/v1/attachments/%s/content" % attachment["id"],
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
summary = {
|
||||
"missing_download": {"status": unavailable_status, "error": json.loads(unavailable_body)["error"]["code"]},
|
||||
"missing_dry_run": missing_dry_run,
|
||||
"missing_apply": missing_apply,
|
||||
"final_dry_run": final_dry_run,
|
||||
"restored_download": {"status": restored_status, "bytes_match": restored_bytes == PNG},
|
||||
"safety": "apply leaves missing PostgreSQL metadata intact; object was restored without metadata recreation",
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, sort_keys=True)
|
||||
print(text)
|
||||
if args.evidence is not None:
|
||||
args.evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.evidence.write_text(text + "\n", encoding="utf-8")
|
||||
if unavailable_status != 503 or missing_dry_run["missing_metadata_objects"] < 1 or missing_apply["deleted_orphans"] != 0 or final_dry_run["missing_metadata_objects"] != 0 or restored_status != 200 or restored_bytes != PNG:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
if "%COMPOSE_ENV_FILE%"=="" set COMPOSE_ENV_FILE=.env
|
||||
echo restart: restarting API, PostgreSQL, Valkey and S3 (volumes preserved)
|
||||
rem The resilience test owns readiness waiting; s3-init has already created bucket.
|
||||
docker compose --env-file %COMPOSE_ENV_FILE% restart --timeout 15 postgres valkey s3 api-1 api-2 nginx
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file %COMPOSE_ENV_FILE% ps
|
||||
echo stack_restarted volumes_preserved
|
||||
exit /b 0
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
|
||||
# Restarts every long-lived API and storage process while preserving volumes.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ENV_FILE="${COMPOSE_ENV_FILE:-.env}"
|
||||
|
||||
printf '%s\n' "restart: restarting API, PostgreSQL, Valkey and S3 (volumes preserved)"
|
||||
# The resilience test owns readiness waiting. The persistent bucket was already
|
||||
# created by the idempotent one-shot s3-init bootstrap service.
|
||||
docker compose --env-file "$ENV_FILE" restart --timeout 15 postgres valkey s3 api-1 api-2 nginx
|
||||
|
||||
docker compose --env-file "$ENV_FILE" ps
|
||||
printf '%s\n' "stack_restarted volumes_preserved"
|
||||
@@ -0,0 +1,17 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
if "%COMPOSE_ENV_FILE%"=="" set COMPOSE_ENV_FILE=.env
|
||||
if "%TARGET_INSTANCE_ID%"=="" (
|
||||
echo TARGET_INSTANCE_ID is required >&2
|
||||
exit /b 2
|
||||
)
|
||||
if not "%TARGET_INSTANCE_ID%"=="api-1" if not "%TARGET_INSTANCE_ID%"=="api-2" (
|
||||
echo Invalid TARGET_INSTANCE_ID: %TARGET_INSTANCE_ID% >&2
|
||||
exit /b 2
|
||||
)
|
||||
echo stop-one: stopping API replica %TARGET_INSTANCE_ID%
|
||||
docker compose --env-file %COMPOSE_ENV_FILE% stop --timeout 10 %TARGET_INSTANCE_ID%
|
||||
if errorlevel 1 exit /b 1
|
||||
echo stop-one: %TARGET_INSTANCE_ID% stopped
|
||||
exit /b 0
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`.
|
||||
# Stops ONE API replica (selected by TARGET_INSTANCE_ID = api-1 or api-2) and
|
||||
# leaves it stopped; the load balancer keeps serving via the remaining replica.
|
||||
# Does not touch postgres, valkey, nginx or any volumes. Restore the replica
|
||||
# explicitly after the test (docker compose start <service>).
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ENV_FILE="${COMPOSE_ENV_FILE:-.env}"
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias (api-1 or api-2)}"
|
||||
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
api-1|api-2) ;;
|
||||
*)
|
||||
printf '%s\n' "stop-one: invalid TARGET_INSTANCE_ID='$TARGET_INSTANCE_ID' (expected api-1 or api-2)" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
printf '%s\n' "stop-one: stopping API replica $TARGET_INSTANCE_ID (nginx keeps serving via the other replica)"
|
||||
docker compose --env-file "$ENV_FILE" stop --timeout 10 "$TARGET_INSTANCE_ID"
|
||||
|
||||
printf '%s\n' "stop-one: $TARGET_INSTANCE_ID stopped"
|
||||
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
schema = json.loads(path.read_text(encoding='utf-8'))
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
|
||||
Reference in New Issue
Block a user