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

zat.dev/zds

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

0
0
68 lines · 2.0 KB Raw History
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Relays that reset during the subscribeRepos handshake must not break the firehose.

A reset handshake is discarded through the handler's close; counting the
connection out there and again in the request handler underflowed the
connection count, which panicked and then refused every subscriber.
"""
import base64
import os
import socket
import sys
import threading
import time


def handshake(host, port, reset):
    s = socket.create_connection((host, port), timeout=5)
    key = base64.b64encode(os.urandom(16)).decode()
    s.sendall((
        "GET /xrpc/com.atproto.sync.subscribeRepos HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\n"
        f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
    ).encode())
    if reset:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, (1).to_bytes(4, "little") + (0).to_bytes(4, "little"))
        s.close()
        return None
    s.settimeout(5)
    status = s.recv(64).split(b"\r\n", 1)[0]
    s.close()
    return status


def main():
    host, port = sys.argv[1], int(sys.argv[2])

    def burst():
        for _ in range(150):
            try:
                handshake(host, port, reset=True)
            except OSError:
                pass

    threads = [threading.Thread(target=burst) for _ in range(16)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    # Reset sockets can still be tearing down; the bug this guards against
    # refused every later subscriber, so a brief retry cannot hide it.
    for _ in range(5):
        status = b""
        for _ in range(40):
            try:
                status = handshake(host, port, reset=False) or b""
            except OSError:
                status = b""
            if b" 101 " in status + b" ":
                break
            time.sleep(0.05)
        assert b" 101 " in status + b" ", status
    print("firehose resets: 2,400 reset handshakes, then subscribeRepos still upgrades")


main()