zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Exercise only a disposable zds-repro-* Fly app with one synthetic resident."""
import argparse
import concurrent.futures
import http.client
import json
import signal
import threading
import time
from urllib.parse import urlencode, urlsplit
DID = "did:plc:zdsbench0000000000000001"
COLLECTION = "dev.zds.repro.record"
def emit(**values):
print(json.dumps({"time": time.time(), **values}), flush=True)
def request(base, path, payload=None, token=None, timeout=15, discard=False):
url = urlsplit(base)
cls = http.client.HTTPSConnection if url.scheme == "https" else http.client.HTTPConnection
conn = cls(url.hostname, url.port, timeout=timeout)
headers = {}
if token:
headers["authorization"] = "Bearer " + token
body = None if payload is None else json.dumps(payload).encode()
if body is not None:
headers["content-type"] = "application/json"
start = time.monotonic()
try:
conn.request("GET" if body is None else "POST", path, body, headers)
response = conn.getresponse()
data = bytearray()
size = 0
while chunk := response.read(65536):
size += len(chunk)
if not discard:
data.extend(chunk)
return response.status, time.monotonic() - start, size, bytes(data)
finally:
conn.close()
def seed(args):
status, _, _, body = request(args.base, "/xrpc/com.atproto.server.createSession",
{"identifier": DID, "password": "password"})
assert status == 200, (status, body)
token = json.loads(body)["accessJwt"]
for first in range(0, args.records, 200):
writes = [{"$type": "com.atproto.repo.applyWrites#create", "collection": COLLECTION,
"rkey": f"r{i:08d}", "value": {"$type": COLLECTION, "index": i,
"text": "synthetic record " + "x" * 480}}
for i in range(first, min(first + 200, args.records))]
status, elapsed, _, body = request(args.base, "/xrpc/com.atproto.repo.applyWrites",
{"repo": DID, "validate": False, "writes": writes}, token, 120)
assert status == 200, (status, body[:500])
if first % 2000 == 0 or first + 200 >= args.records:
emit(phase="seed", records=min(first + 200, args.records), seconds=elapsed)
emit(phase="seed_complete", records=args.records)
def exercise(args):
read_path = "/xrpc/com.atproto.repo.listRecords?" + urlencode(
{"repo": DID, "collection": COLLECTION, "limit": 1})
export_path = "/xrpc/com.atproto.sync.getRepo?" + urlencode({"did": DID})
if args.since:
status, _, _, body = request(args.base, "/xrpc/com.atproto.sync.getLatestCommit?" + urlencode({"did": DID}))
assert status == 200, (status, body)
export_path += "&" + urlencode({"since": json.loads(body)["rev"]})
stop = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stop.set())
signal.signal(signal.SIGINT, lambda *_: stop.set())
def lane(name, path, interval, duration):
start = time.monotonic()
samples = []
failures = 0
index = 0
while time.monotonic() - start < duration and not stop.is_set():
request_start = time.monotonic()
try:
status, elapsed, size, body = request(args.base, path, timeout=12, discard=name.startswith("export"))
if name == "read" and status == 200:
assert len(json.loads(body)["records"]) == 1
failures += status != 200
samples.append(elapsed)
if name.startswith("export") or name == "homepage" or elapsed >= 1 or status != 200:
emit(phase=name, status=status, seconds=elapsed, bytes=size)
except (OSError, http.client.HTTPException) as exc:
failures += 1
emit(phase=name, error=str(exc), seconds=time.monotonic() - request_start)
index += 1
stop.wait(max(0, start + index * interval - time.monotonic()))
samples.sort()
emit(phase=name + "_summary", attempts=index, failures=failures,
timing_scope="completed HTTP responses; timeout durations are logged separately",
p50=samples[len(samples)//2] if samples else None,
p95=samples[min(len(samples)-1, int(len(samples)*.95))] if samples else None,
maximum=max(samples, default=None))
emit(phase="control_start", seconds=15)
lane("control", read_path, .5, 15)
emit(phase="pressure_start", seconds=args.seconds, interval=args.interval, since=args.since,
exporters=args.exporters, homepage_interval=args.homepage_interval)
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=args.exporters + 3) as pool:
futures = [pool.submit(lane, "read", read_path, .5, args.seconds),
pool.submit(lane, "health", "/xrpc/_health", 1, args.seconds)]
futures.extend(pool.submit(lane, f"export{i}", export_path, args.interval, args.seconds)
for i in range(args.exporters))
if args.homepage_interval:
futures.append(pool.submit(lane, "homepage", "/", args.homepage_interval, args.seconds))
for future in futures:
future.result()
finally:
stop.set()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("base")
parser.add_argument("--seed", action="store_true")
parser.add_argument("--records", type=int, default=50000)
parser.add_argument("--seconds", type=float, default=480)
parser.add_argument("--interval", type=float, default=10)
parser.add_argument("--since", action="store_true")
parser.add_argument("--exporters", type=int, default=1)
parser.add_argument("--homepage-interval", type=float, default=0)
args = parser.parse_args()
host = urlsplit(args.base).hostname or ""
if not host.startswith("zds-repro-") or not host.endswith(".fly.dev"):
parser.error("target must be a disposable zds-repro-*.fly.dev app")
if args.interval <= 0 or args.seconds <= 0 or args.records < 1 or args.exporters < 0 or args.homepage_interval < 0:
parser.error("records, interval and seconds must be positive")
if args.seed:
seed(args)
else:
exercise(args)
if __name__ == "__main__":
main()