~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
279 lines · 13.7 KB Raw History
#!/usr/bin/env python3
"""Drive one fixed sequence of writes through a PDS and record a transcript.

The same scenario runs against zds and the reference PDS, so every request is
deterministic apart from what the server chooses (DIDs, revs, TIDs, tokens).
Each step names the status it expects; an unexpected status fails the run.
The transcript is normalized later by diff.py, so it keeps raw responses.

stdlib only, so it runs anywhere the harness does (zlay's CI included).
"""

import argparse
import base64
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

# a 1x1 PNG, so both servers sniff the same MIME type
PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
)
CREATED_AT = "2026-01-01T00:00:00.000Z"
PASSWORD = "interop-password-1"


class Failed(Exception):
    pass


class Client:
    def __init__(self, base, out):
        self.base = base.rstrip("/")
        self.steps = out

    def call(self, step, method, nsid, *, body=None, params=None, token=None,
             raw=None, content_type=None, expect=200, admin=None):
        url = f"{self.base}/xrpc/{nsid}"
        if params:
            url += "?" + urllib.parse.urlencode(params)
        headers = {}
        data = None
        if raw is not None:
            data = raw
            headers["content-type"] = content_type or "application/octet-stream"
        elif body is not None:
            data = json.dumps(body).encode()
            headers["content-type"] = "application/json"
        if token:
            headers["authorization"] = f"Bearer {token}"
        if admin:
            headers["authorization"] = "Basic " + base64.b64encode(f"admin:{admin}".encode()).decode()
        req = urllib.request.Request(url, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                status, payload, ctype = resp.status, resp.read(), resp.headers.get("content-type", "")
        except urllib.error.HTTPError as err:
            status, payload, ctype = err.code, err.read(), err.headers.get("content-type", "")
        parsed = None
        if "json" in ctype:
            try:
                parsed = json.loads(payload)
            except ValueError:
                parsed = None
        entry = {
            "step": step,
            "method": method,
            "nsid": nsid,
            "params": params,
            "body": body,
            "status": status,
            "contentType": ctype.split(";")[0].strip(),
            "response": parsed,
        }
        self.steps.append(entry)
        expected = expect if isinstance(expect, (list, tuple)) else [expect]
        if status not in expected:
            raise Failed(f"{step}: {method} {nsid} returned {status}, expected {expect}: {payload[:400]!r}")
        return parsed


def post(text, **extra):
    rec = {"$type": "app.bsky.feed.post", "text": text, "createdAt": CREATED_AT}
    rec.update(extra)
    return rec


def run(base, handle_domain, out, settle):
    steps = []
    accounts = {}
    try:
        scenario(Client(base, steps), accounts, handle_domain)
    finally:
        result = {"base": base, "accounts": {k: {"did": v["did"], "handle": v["handle"]} for k, v in accounts.items()},
                  "steps": steps}
        if out:
            with open(out, "w") as f:
                json.dump(result, f, indent=2)
                f.write("\n")
    # give the firehose consumers a moment to see the last events
    time.sleep(settle)
    return result


def scenario(c, accounts, handle_domain):

    c.call("describe server", "GET", "com.atproto.server.describeServer")

    for name in ("alice", "bob"):
        handle = f"{name}{handle_domain}"
        r = c.call(f"create {name}", "POST", "com.atproto.server.createAccount", body={
            "handle": handle, "email": f"{name}@interop.invalid", "password": PASSWORD,
        })
        accounts[name] = {"did": r["did"], "jwt": r["accessJwt"], "handle": handle}
    a, b = accounts["alice"], accounts["bob"]

    r = c.call("alice signs in", "POST", "com.atproto.server.createSession",
               body={"identifier": a["handle"], "password": PASSWORD})
    a["jwt"] = r["accessJwt"]
    c.call("alice session", "GET", "com.atproto.server.getSession", token=a["jwt"])
    c.call("wrong password", "POST", "com.atproto.server.createSession",
           body={"identifier": a["handle"], "password": "nope"}, expect=401)

    def write(step, nsid, who, body, expect=200):
        return c.call(step, "POST", nsid, body={"repo": who["did"], **body}, token=who["jwt"], expect=expect)

    # profile: put as create, then put as update
    profile = {"$type": "app.bsky.actor.profile", "displayName": "Alice", "description": "interop"}
    write("alice profile create", "com.atproto.repo.putRecord", a,
          {"collection": "app.bsky.actor.profile", "rkey": "self", "record": profile})
    write("alice profile update", "com.atproto.repo.putRecord", a,
          {"collection": "app.bsky.actor.profile", "rkey": "self", "record": {**profile, "displayName": "Alice A."}})

    # posts with server-chosen and client-chosen rkeys
    posts = []
    for i in range(12):
        r = write(f"alice post {i}", "com.atproto.repo.createRecord", a,
                  {"collection": "app.bsky.feed.post", "record": post(f"post {i}")})
        posts.append(r)
    write("alice post with rkey", "com.atproto.repo.createRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": "3interopfixed", "record": post("fixed rkey")})
    write("duplicate rkey", "com.atproto.repo.createRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": "3interopfixed", "record": post("again")}, expect=(400, 500))

    # cross-account references
    write("bob follows alice", "com.atproto.repo.createRecord", b,
          {"collection": "app.bsky.graph.follow", "record": {
              "$type": "app.bsky.graph.follow", "subject": a["did"], "createdAt": CREATED_AT}})
    like = write("bob likes a post", "com.atproto.repo.createRecord", b,
          {"collection": "app.bsky.feed.like", "record": {
              "$type": "app.bsky.feed.like", "createdAt": CREATED_AT,
              "subject": {"uri": posts[0]["uri"], "cid": posts[0]["cid"]}}})

    # a blob and a post that embeds it
    blob = c.call("alice uploads a blob", "POST", "com.atproto.repo.uploadBlob",
                  raw=PNG, content_type="image/png", token=a["jwt"])["blob"]
    write("alice posts the image", "com.atproto.repo.createRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": "3interopimage", "record": post("image", embed={
              "$type": "app.bsky.embed.images",
              "images": [{"alt": "a pixel", "image": blob, "aspectRatio": {"width": 1, "height": 1}}]})})

    # one batch with every op kind
    write("alice batch", "com.atproto.repo.applyWrites", a, {"writes": [
        {"$type": "com.atproto.repo.applyWrites#create", "collection": "app.bsky.feed.post",
         "rkey": "3interopbtcha", "value": post("batch 1")},
        {"$type": "com.atproto.repo.applyWrites#create", "collection": "app.bsky.feed.post",
         "rkey": "3interopbtchb", "value": post("batch 2")},
        {"$type": "com.atproto.repo.applyWrites#update", "collection": "app.bsky.feed.post",
         "rkey": "3interopfixed", "value": post("fixed rkey, edited")},
        {"$type": "com.atproto.repo.applyWrites#delete", "collection": "app.bsky.feed.post",
         "rkey": posts[1]["uri"].rsplit("/", 1)[1]},
    ]})

    # enough small records in one collection to give the MST some depth
    for chunk in range(3):
        write(f"alice bulk {chunk}", "com.atproto.repo.applyWrites", a, {"writes": [
            {"$type": "com.atproto.repo.applyWrites#create", "collection": "com.example.interop.item",
             "rkey": f"item-{chunk:02d}-{i:03d}", "value": {"$type": "com.example.interop.item", "n": chunk * 100 + i}}
            for i in range(40)
        ]})
    # rkey characters at the edges of the record key grammar
    for rkey in ("a:b", "x~y", "under_score", "dot.ted", "dash-ed"):
        write(f"alice rkey {rkey}", "com.atproto.repo.putRecord", a,
              {"collection": "com.example.interop.item", "rkey": rkey,
               "record": {"$type": "com.example.interop.item", "rkey": rkey}})

    # deletes over fixed keys, so the MST shapes they collapse are the same
    # every run: single deletes, then a batch that empties a key range
    for i in range(0, 40, 3):
        write(f"alice deletes item 00-{i:03d}", "com.atproto.repo.deleteRecord", a,
              {"collection": "com.example.interop.item", "rkey": f"item-00-{i:03d}"})
    write("alice deletes a range", "com.atproto.repo.applyWrites", a, {"writes": [
        {"$type": "com.atproto.repo.applyWrites#delete", "collection": "com.example.interop.item",
         "rkey": f"item-01-{i:03d}"} for i in range(10, 30)
    ]})

    # churn over server-chosen keys: their MST shapes differ every run, so
    # this is where commits that drop proof nodes usually show up
    churn = [write(f"alice churn post {i}", "com.atproto.repo.createRecord", a,
                   {"collection": "app.bsky.feed.post", "record": post(f"churn {i}")}) for i in range(30)]
    for i, r in enumerate(churn):
        if i % 2 == 0:
            write(f"alice churn delete {i}", "com.atproto.repo.deleteRecord", a,
                  {"collection": "app.bsky.feed.post", "rkey": r["uri"].rsplit("/", 1)[1]})

    # deletes, including the one record that leaves a collection empty
    write("alice deletes a post", "com.atproto.repo.deleteRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": posts[2]["uri"].rsplit("/", 1)[1]})
    write("bob unlikes", "com.atproto.repo.deleteRecord", b,
          {"collection": "app.bsky.feed.like", "rkey": like["uri"].rsplit("/", 1)[1]})
    write("delete a missing record", "com.atproto.repo.deleteRecord", b,
          {"collection": "app.bsky.feed.like", "rkey": "3nothinghere2"})

    # a swapCommit that lost the race
    stale = c.call("alice latest commit", "GET", "com.atproto.sync.getLatestCommit", params={"did": a["did"]})
    write("alice writes after reading the head", "com.atproto.repo.createRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": "3interopswapa", "record": post("swap ok"),
           "swapCommit": stale["cid"]})
    write("stale swapCommit", "com.atproto.repo.createRecord", a,
          {"collection": "app.bsky.feed.post", "rkey": "3interopswapb", "record": post("swap stale"),
           "swapCommit": stale["cid"]}, expect=400)
    current = c.call("alice profile record", "GET", "com.atproto.repo.getRecord",
                     params={"repo": a["did"], "collection": "app.bsky.actor.profile", "rkey": "self"})
    write("stale swapRecord", "com.atproto.repo.putRecord", a,
          {"collection": "app.bsky.actor.profile", "rkey": "self", "record": profile,
           "swapRecord": posts[0]["cid"]}, expect=400)
    write("matching swapRecord", "com.atproto.repo.putRecord", a,
          {"collection": "app.bsky.actor.profile", "rkey": "self", "record": profile,
           "swapRecord": current["cid"]})

    # identity and account events
    new_handle = f"alice2{handle_domain}"
    c.call("alice changes handle", "POST", "com.atproto.identity.updateHandle",
           body={"handle": new_handle}, token=a["jwt"])
    c.call("resolve the new handle", "GET", "com.atproto.identity.resolveHandle", params={"handle": new_handle})
    c.call("bob deactivates", "POST", "com.atproto.server.deactivateAccount", body={}, token=b["jwt"])
    c.call("deactivated repo status", "GET", "com.atproto.sync.getRepoStatus", params={"did": b["did"]})
    c.call("bob reactivates", "POST", "com.atproto.server.activateAccount", token=b["jwt"])
    write("bob posts after reactivating", "com.atproto.repo.createRecord", b,
          {"collection": "app.bsky.feed.post", "rkey": "3interopbacks", "record": post("back")})

    # reads, for the response diff
    for who in ("alice", "bob"):
        did = accounts[who]["did"]
        c.call(f"{who} describeRepo", "GET", "com.atproto.repo.describeRepo", params={"repo": did})
        c.call(f"{who} repo status", "GET", "com.atproto.sync.getRepoStatus", params={"did": did})
    c.call("alice lists posts", "GET", "com.atproto.repo.listRecords",
           params={"repo": a["did"], "collection": "app.bsky.feed.post", "limit": 5})
    c.call("alice lists posts reversed", "GET", "com.atproto.repo.listRecords",
           params={"repo": a["did"], "collection": "app.bsky.feed.post", "limit": 5, "reverse": "true"})
    c.call("get a missing record", "GET", "com.atproto.repo.getRecord",
           params={"repo": a["did"], "collection": "app.bsky.feed.post", "rkey": "3nothinghere2"}, expect=400)
    c.call("alice blobs", "GET", "com.atproto.sync.listBlobs", params={"did": a["did"]})
    c.call("list repos", "GET", "com.atproto.sync.listRepos")
    c.call("unknown repo", "GET", "com.atproto.sync.getLatestCommit",
           params={"did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"}, expect=(400, 404))



def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--pds", required=True, help="PDS base URL")
    p.add_argument("--handle-domain", default=".test", help="handle suffix the PDS serves")
    p.add_argument("--out", help="write the transcript JSON here")
    p.add_argument("--settle", type=float, default=0.5, help="seconds to wait after the last write")
    args = p.parse_args()
    try:
        r = run(args.pds, args.handle_domain, args.out, args.settle)
    except Failed as err:
        print(f"scenario failed: {err}", file=sys.stderr)
        sys.exit(1)
    dids = ", ".join(f"{k}={v['did']}" for k, v in r["accounts"].items())
    print(f"scenario: {len(r['steps'])} requests against {args.pds} ({dids})")


if __name__ == "__main__":
    main()