askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
exchange_harness.py · 8.2 KB · 200 lines
| 1 | """Two companies' boxes in one process, wired by an in-process transport. |
| 2 | |
| 3 | Each box is a scripts/try_package Sandbox (its own data directory, objects |
| 4 | directory, admin token and users, enforcement on). The server reads its data |
| 5 | directory from the environment, so a call to a box runs with that box's |
| 6 | environment set, and the previous one is put back afterwards -- including |
| 7 | when box A's object, mid-request, calls box B through the transport, which is |
| 8 | why the transport runs B's request on its own thread (A's event loop is busy |
| 9 | running A's object) while A waits. |
| 10 | |
| 11 | The transport replaces object_exchange's urllib transport: a request for |
| 12 | https://<domain>/... is answered by the box with that domain through the real |
| 13 | ASGI app, raw bytes in and out. No socket is opened; `no_sockets` makes any |
| 14 | attempt fail the test. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import asyncio |
| 20 | import contextlib |
| 21 | import os |
| 22 | import socket |
| 23 | import threading |
| 24 | import urllib.parse |
| 25 | from typing import Any |
| 26 | |
| 27 | import pytest |
| 28 | |
| 29 | import object_exchange |
| 30 | import object_server |
| 31 | from scripts.try_package import Sandbox, _asgi |
| 32 | |
| 33 | _ENV = (object_server.DATA_DIR_ENV, object_server.ADMIN_TOKEN_ENV, "DBBASIC_OBJECTS_DIR", |
| 34 | object_server.PERMISSION_ENFORCEMENT_ENV, object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV) |
| 35 | |
| 36 | |
| 37 | class Box: |
| 38 | def __init__(self, sandbox: Sandbox, domain: str, name: str): |
| 39 | self.sandbox = sandbox |
| 40 | self.domain = domain |
| 41 | self.name = name |
| 42 | self.env = {object_server.DATA_DIR_ENV: str(sandbox.data_dir), |
| 43 | object_server.ADMIN_TOKEN_ENV: sandbox.admin_token, |
| 44 | "DBBASIC_OBJECTS_DIR": str(sandbox.objects_dir), |
| 45 | object_server.PERMISSION_ENFORCEMENT_ENV: "true", |
| 46 | object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV: "true"} |
| 47 | |
| 48 | @property |
| 49 | def data_dir(self): |
| 50 | return self.sandbox.data_dir |
| 51 | |
| 52 | @contextlib.contextmanager |
| 53 | def active(self): |
| 54 | saved = {name: os.environ.get(name) for name in _ENV} |
| 55 | os.environ.update(self.env) |
| 56 | try: |
| 57 | yield self |
| 58 | finally: |
| 59 | for name, value in saved.items(): |
| 60 | if value is None: |
| 61 | os.environ.pop(name, None) |
| 62 | else: |
| 63 | os.environ[name] = value |
| 64 | |
| 65 | def call(self, user: str, method: str, path: str, body: Any = None) -> tuple[int, Any]: |
| 66 | with self.active(): |
| 67 | return self.sandbox.call(user, method, path, body) |
| 68 | |
| 69 | def add_user(self, user: str, roles=()): |
| 70 | with self.active(): |
| 71 | return self.sandbox.add_user(user, roles=roles) |
| 72 | |
| 73 | def admin(self, op: str, user: str = "owner", **fields) -> tuple[int, Any]: |
| 74 | return self.call(user, "POST", "/objects/action_exchange_admin", {"op": op, **fields}) |
| 75 | |
| 76 | def records(self, collection: str, user: str = "admin") -> list[dict[str, Any]]: |
| 77 | status, body = self.call(user, "GET", f"/collections/{collection}/records?limit=500") |
| 78 | assert status == 200, (collection, status, body) |
| 79 | return body["records"] |
| 80 | |
| 81 | def deliver(self) -> dict[str, Any]: |
| 82 | status, body = self.call("admin", "POST", "/objects/system_exchange_deliver", {}) |
| 83 | assert status == 200, body |
| 84 | return body |
| 85 | |
| 86 | def send(self, collection: str, record_id: str, user: str = "owner", **extra): |
| 87 | return self.call(user, "POST", "/objects/action_exchange_send", |
| 88 | {"collection": collection, "record_id": record_id, **extra}) |
| 89 | |
| 90 | |
| 91 | class Network: |
| 92 | """domain -> Box; `transport` is installed as object_exchange's transport.""" |
| 93 | |
| 94 | def __init__(self): |
| 95 | self.boxes: dict[str, Box] = {} |
| 96 | self.requests: list[tuple[str, str]] = [] |
| 97 | self.down: set[str] = set() |
| 98 | self.tamper = None # optional callable(bytes) -> bytes applied to POST bodies |
| 99 | |
| 100 | def add(self, box: Box) -> Box: |
| 101 | self.boxes[box.domain] = box |
| 102 | return box |
| 103 | |
| 104 | def transport(self, method: str, url: str, body: bytes, headers) -> tuple[int, bytes]: |
| 105 | parts = urllib.parse.urlsplit(url) |
| 106 | assert parts.scheme == "https", url |
| 107 | self.requests.append((method, url)) |
| 108 | box = self.boxes.get(parts.hostname or "") |
| 109 | if box is None or box.domain in self.down: |
| 110 | raise object_exchange.TransportError(f"no route to {parts.hostname}") |
| 111 | if self.tamper and method == "POST": |
| 112 | body = self.tamper(body) |
| 113 | result: dict[str, Any] = {} |
| 114 | |
| 115 | def run(): |
| 116 | try: |
| 117 | with box.active(): |
| 118 | result["value"] = asyncio.run(_asgi( |
| 119 | parts.path, method, parts.query, body, list(dict(headers).items()))) |
| 120 | except BaseException as exc: # surfaced in the caller's thread |
| 121 | result["error"] = exc |
| 122 | |
| 123 | thread = threading.Thread(target=run) |
| 124 | thread.start() |
| 125 | thread.join() |
| 126 | if "error" in result: |
| 127 | raise result["error"] |
| 128 | return result["value"] |
| 129 | |
| 130 | |
| 131 | @contextlib.contextmanager |
| 132 | def no_sockets(): |
| 133 | """Fail loudly if anything in the exchange tries the real network.""" |
| 134 | def refuse(*args, **kwargs): |
| 135 | raise AssertionError("the exchange tests must not open a network connection") |
| 136 | |
| 137 | saved = (socket.socket.connect, socket.socket.connect_ex, socket.create_connection, |
| 138 | socket.getaddrinfo) |
| 139 | socket.socket.connect = refuse |
| 140 | socket.socket.connect_ex = refuse |
| 141 | socket.create_connection = refuse |
| 142 | socket.getaddrinfo = refuse |
| 143 | try: |
| 144 | yield |
| 145 | finally: |
| 146 | (socket.socket.connect, socket.socket.connect_ex, socket.create_connection, |
| 147 | socket.getaddrinfo) = saved |
| 148 | |
| 149 | |
| 150 | @contextlib.contextmanager |
| 151 | def two_companies(packages_buyer, packages_seller=None, *, buyer="shop.example", |
| 152 | seller="supplier.example"): |
| 153 | """A buyer's box and a seller's box, each set up for exchange, with an |
| 154 | `owner` (role owner) and a `clerk` user, not yet connected. |
| 155 | |
| 156 | Skips the calling test when the `exchange` extra is not installed: every |
| 157 | box generates a signing key at setup, which needs `cryptography`. CI |
| 158 | installs the extra, but a plain `.[test]` install must still give a |
| 159 | green run, not a page of setup errors.""" |
| 160 | if not object_exchange.available(): |
| 161 | pytest.skip("needs the exchange extra: pip install -e '.[exchange]'") |
| 162 | network = Network() |
| 163 | with contextlib.ExitStack() as stack: |
| 164 | stack.enter_context(no_sockets()) |
| 165 | boxes = [] |
| 166 | for name, domain, packages in (("buyer", buyer, packages_buyer), |
| 167 | ("seller", seller, packages_seller or packages_buyer)): |
| 168 | saved = {name_: os.environ.get(name_) for name_ in _ENV} |
| 169 | sandbox = stack.enter_context(Sandbox(["app-exchange", *packages])) |
| 170 | box = network.add(Box(sandbox, domain, name)) |
| 171 | # Leave the process environment as it was; each call sets its own. |
| 172 | for name_, value in saved.items(): |
| 173 | if value is None: |
| 174 | os.environ.pop(name_, None) |
| 175 | else: |
| 176 | os.environ[name_] = value |
| 177 | # The business's owner is also its staff: invoice money, |
| 178 | # payments and order status are role:manager's (app-invoices |
| 179 | # 0.15.0, app-payments 0.8.0), and the owner runs the books. |
| 180 | box.add_user("owner", roles=["owner", "manager"]) |
| 181 | box.add_user("clerk") |
| 182 | status, body = box.admin("setup", domain=domain, |
| 183 | company_name=f"{name.title()} Ltd") |
| 184 | assert status == 200, body |
| 185 | boxes.append(box) |
| 186 | object_exchange.set_transport(network.transport) |
| 187 | stack.callback(object_exchange.set_transport, None) |
| 188 | yield network, boxes[0], boxes[1] |
| 189 | |
| 190 | |
| 191 | def connect(buyer: Box, seller: Box) -> None: |
| 192 | status, body = buyer.admin("connect", domain=seller.domain) |
| 193 | assert status == 200, body |
| 194 | pending = [p for p in seller.records("trading_partners") if p["domain"] == buyer.domain] |
| 195 | assert pending and pending[0]["status"] == "pending", pending |
| 196 | status, body = seller.admin("accept", partner_id=pending[0]["id"]) |
| 197 | assert status == 200, body |
| 198 | for box, other in ((buyer, seller), (seller, buyer)): |
| 199 | row = [p for p in box.records("trading_partners") if p["domain"] == other.domain][0] |
| 200 | assert row["status"] == "connected", (box.name, row) |