#!/usr/bin/env python3 """Drives forge-service over its socket as the desktop GUI would, against a real loreserver and lore-forge. Run by scripts/e2e-lore.sh, which starts everything and passes: desktop-e2e.py SOCKET FORGE_URL COOKIE_JAR LORE_REMOTE WORK_DIR LORE_CLI BOB_WORKING_COPY Signs in through the device flow (approving it as the cookie jar's user), lists and clones alice/demo, reads files, history and a revision, submits some of the local changes, then adds the CLI's working copy and syncs it. Then locks and policies, with bob (a writer on alice/demo, through the `lore` CLI in his own working copy) on the other side: bob's lock reaches alice's service, her edit to his file is warned about and refused on submit, she force-releases it, a submit releases her own locks, lock-on-edit takes the lock of an edited binary file, autosync pulls bob's push, and holds back when her edits overlap his. Exits nonzero with a message on the first failure. """ import json import os import socket import subprocess import sys import time import urllib.parse import urllib.request TIMEOUT_S = 60 def fail(message): print(f"FAIL: {message}", file=sys.stderr) sys.exit(1) class Service: def __init__(self, path): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(path) self.sock.settimeout(TIMEOUT_S) self.buffer = b"" self.next_id = 0 self.notifications = [] self.notices = [] self.responses = {} def _read(self): while b"\n" not in self.buffer: chunk = self.sock.recv(65536) if not chunk: fail("the service closed the connection") self.buffer += chunk line, self.buffer = self.buffer.split(b"\n", 1) message = json.loads(line) if "method" in message: self.notifications.append(message) if message["method"] == "notice": self.notices.append(message["params"]["message"]) else: self.responses[message["id"]] = message def send(self, method, params=None): self.next_id += 1 line = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}} self.sock.sendall(json.dumps(line).encode() + b"\n") return self.next_id def response(self, id): while id not in self.responses: self._read() return self.responses.pop(id) def call(self, method, params=None): answer = self.response(self.send(method, params)) if "error" in answer: fail(f"{method}: {answer['error']['message']}") return answer["result"] def refused(self, method, params, code): """Calls `method` expecting error `code`; returns the error message.""" answer = self.response(self.send(method, params)) if "error" not in answer: fail(f"{method} {params} was not refused") if answer["error"]["code"] != code: fail(f"{method} was refused with {answer['error']}, not code {code}") return answer["error"]["message"] def until(self, what, check, timeout=TIMEOUT_S): """Polls `check` (which may make calls) until it returns something true.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: value = check() if value: return value time.sleep(0.3) fail(f"timed out waiting for {what}") def notice(self, text, timeout=TIMEOUT_S): """Waits for a notice containing `text`.""" def seen(): # A cheap call reads whatever has arrived. self.call("status") return next((n for n in self.notices if text in n), None) return self.until(f"a notice about {text!r}", seen, timeout) def wait(self, method, match): """The first notification `method` whose params satisfy `match`, dropping those before.""" deadline = time.monotonic() + TIMEOUT_S while time.monotonic() < deadline: while self.notifications: note = self.notifications.pop(0) if note["method"] == method and match(note["params"]): return note["params"] self._read() fail(f"no {method} notification in {TIMEOUT_S}s") def finished(self, workspace, kind): params = self.wait( "activity", lambda p: p["workspace"] == workspace and p["kind"] == kind and p["phase"] in ("finished", "failed"), ) if params["phase"] == "failed": fail(f"{kind} failed: {params.get('message', '')}") return params def approve(forge, jar, code): """Approves a device code on the forge as the user whose session cookie is in `jar`.""" cookies = {} with open(jar) as f: for line in f: line = line.strip() if line.startswith("#HttpOnly_"): line = line[len("#HttpOnly_"):] elif not line or line.startswith("#"): continue fields = line.split("\t") if len(fields) == 7: cookies[fields[5]] = fields[6] header = "; ".join(f"{k}={v}" for k, v in cookies.items()) body = urllib.parse.urlencode({"csrf": cookies["lf_csrf"], "user_code": code, "decision": "approve"}).encode() request = urllib.request.Request( f"{forge}/device", data=body, headers={"Cookie": header, "Origin": forge}, method="POST" ) with urllib.request.urlopen(request, timeout=TIMEOUT_S) as answer: if "Client signed in" not in answer.read().decode(): fail("the forge did not approve the desktop sign-in") def main(): sock_path, forge, jar, remote, work, lore_cli, bob_wc = sys.argv[1:8] service = Service(sock_path) step = lambda text: print(f" {text}") hello = service.call("hello", {"protocol": 3, "client": "desktop-e2e"}) step(f"hello: {hello['service']}") status = service.call("status") if "loaded" not in status["liblore"]: fail(f"liblore did not load: {status['liblore']}") step(f"liblore {status['liblore']['loaded']['version']}") # Sign in: the service starts liblore's device flow and says which code to approve. service.call("login", {"remote": remote}) waiting = service.wait("login", lambda p: p["phase"] in ("waiting", "failed") and (p.get("code") or p["phase"] == "failed")) if waiting["phase"] == "failed": fail(f"sign-in failed: {waiting.get('message')}") step(f"user code {waiting['code']}") approve(forge, jar, waiting["code"]) done = service.wait("login", lambda p: p["phase"] in ("done", "failed")) if done["phase"] != "done" or done.get("message") != "alice": fail(f"sign-in ended {done}") accounts = service.call("status")["accounts"] # With no working copy yet to resolve names through, the account carries the username. if not any(a.get("name") == "alice" for a in accounts): fail(f"status does not list alice's account: {accounts}") step("signed in as alice") names = [r["name"] for r in service.call("repositories", {"remote": remote})["repositories"]] if "alice/demo" not in names: fail(f"repositories lacks alice/demo: {names}") step(f"repositories {names}") # Clone, then read it back as the explorer does. into = os.path.join(work, "desktop-clone") ws = service.call("workspace_clone", {"url": f"{remote}/alice/demo", "path": into})["id"] service.finished(ws, "clone") with open(os.path.join(into, "a.txt")) as f: if f.read().strip() != "two": fail("the clone's a.txt is not the latest") root = service.call("files", {"workspace": ws, "path": ""})["entries"] listed = {(e["name"], e["dir"]) for e in root} for want in [("sub", True), ("a.txt", False), ("c.txt", False), ("d.txt", False)]: if want not in listed: fail(f"files lacks {want}: {sorted(listed)}") if root[0]["name"] != "sub": fail("files does not list directories first") history = service.call("history", {"workspace": ws}) branches = {b["name"] for b in history["branches"]} if not {"main", "feature"} <= branches: fail(f"history lacks a branch: {branches}") messages = [r["message"] for r in history["revisions"]] for want in ["First revision", "Second revision", "Feature work", "Main moves on"]: if want not in messages: fail(f"history lacks {want!r}: {messages}") # liblore names the signed-in user by username and others by display name. if any(r["author"] != "alice" for r in history["revisions"] if r["message"]): fail(f"history does not name alice as the author: {sorted({r['author'] for r in history['revisions']})}") merge = history["revisions"][0] if len(merge["parents"]) != 2: fail(f"the newest revision is not the merge: {merge}") second = next(r for r in history["revisions"] if r["message"] == "Second revision") changed = {(c["path"], c["action"]) for c in service.call("revision", {"workspace": ws, "signature": second["signature"]})["changes"]} if changed != {("a.txt", "modify"), ("sub/b.txt", "add")}: fail(f"the second revision's changes are {changed}") file_history = [r["message"] for r in service.call("file_history", {"workspace": ws, "path": "a.txt"})["revisions"]] if file_history[:2] != ["Second revision", "First revision"]: fail(f"a.txt's history is {file_history}") step(f"clone reads back: {len(messages)} revisions, branches {sorted(branches)}") # Local changes, and a submit of some of them. with open(os.path.join(into, "a.txt"), "w") as f: f.write("five\n") for name in ("e.txt", "kept.txt"): with open(os.path.join(into, name), "w") as f: f.write(name + "\n") service.call("refresh", {"workspace": ws}) changes = {(c["path"], c["action"]) for c in service.call("changes", {"workspace": ws})["changes"]} if changes != {("a.txt", "modify"), ("e.txt", "add"), ("kept.txt", "add")}: fail(f"changes are {changes}") service.call("submit", {"workspace": ws, "message": "From the desktop", "paths": ["a.txt", "e.txt"]}) pushed = service.finished(ws, "submit").get("transfer") if not pushed or pushed["direction"] != "up" or pushed["bytes_done"] <= 0: fail(f"the submit's transfer is {pushed}") left = [c["path"] for c in service.call("changes", {"workspace": ws})["changes"]] if left != ["kept.txt"]: fail(f"after submit the changes are {left}") newest = service.call("history", {"workspace": ws})["revisions"][0] if newest["message"] != "From the desktop" or newest["author"] != "alice": fail(f"the newest revision is {newest}") step(f"submitted r{newest['number']}, kept.txt left out; pushed {pushed['bytes_done']} bytes") # The CLI's working copy, added and synced: it gets the desktop's revision. cli = os.path.join(work, "alice-work") with open(os.path.join(cli, "local.txt"), "w") as f: f.write("local\n") cli_ws = service.call("workspace_add", {"path": cli})["id"] service.call("sync_now", {"workspace": cli_ws}) fetched = service.finished(cli_ws, "sync").get("transfer") if not fetched or fetched["direction"] != "down" or fetched["bytes_done"] <= 0: fail(f"the sync's transfer is {fetched}") with open(os.path.join(cli, "a.txt")) as f: if f.read().strip() != "five": fail("sync did not bring a.txt from the desktop's submit") if not os.path.exists(os.path.join(cli, "e.txt")) or os.path.exists(os.path.join(cli, "kept.txt")): fail("sync did not bring exactly the submitted files") synced = [c["path"] for c in service.call("changes", {"workspace": cli_ws})["changes"]] if synced != ["local.txt"]: fail(f"sync lost or invented local changes: {synced}") status = service.call("status") ws_state = {w["id"]: w for w in status["workspaces"]} if ws_state[cli_ws]["revision"] != newest["number"]: fail(f"the synced workspace is at r{ws_state[cli_ws]['revision']}, not r{newest['number']}") step(f"working copy synced to r{newest['number']}, local.txt kept; fetched {fetched['bytes_done']} bytes") service.call("workspace_remove", {"workspace": cli_ws}) locks_and_policies(service, ws, into, lore_cli, bob_wc) service.call("shutdown") def write(path, text): with open(path, "w") as f: f.write(text) def read(path): with open(path) as f: return f.read() def locks_and_policies(service, ws, into, lore_cli, bob_wc): step = lambda text: print(f" {text}") bob_env = dict(os.environ, LORE_AUTH_PATH=os.path.join(os.path.dirname(bob_wc), "auth-bob")) def bob(*args): done = subprocess.run([lore_cli, *args], cwd=bob_wc, env=bob_env, capture_output=True, text=True) if done.returncode != 0: fail(f"bob: lore {' '.join(args)}: {done.stdout}{done.stderr}") return done.stdout def locks(): return {l["path"]: l for l in service.call("locks", {"workspace": ws})["locks"]} def changes(): return {c["path"]: c for c in service.call("changes", {"workspace": ws})["changes"]} # kept.txt is still a local change from the submit above; it stays out of the way. got = service.call("lock", {"workspace": ws, "paths": ["a.txt"]}) if got["locked"] != ["a.txt"]: fail(f"lock answered {got}") if service.call("lock", {"workspace": ws, "paths": ["a.txt"]})["already"] != ["a.txt"]: fail("locking again does not report the lock as already held") mine = locks().get("a.txt") if not mine or not mine["mine"] or mine["owner"] != "alice": fail(f"locks shows {mine}") step("alice locks a.txt") bob("sync") bob("lock", "acquire", "d.txt") held = service.until("bob's lock to reach alice", lambda: locks().get("d.txt")) if held["mine"] or held["owner"] != "Bob Example": fail(f"bob's lock shows as {held}") step("bob's lock on d.txt reaches alice's service") write(os.path.join(into, "d.txt"), "alice's edit\n") service.notice("d.txt is locked by Bob Example") change = service.until("d.txt in changes", lambda: changes().get("d.txt")) if change["lock"] != "Bob Example" or change["lock_mine"]: fail(f"changes shows d.txt as {change}") message = service.refused("submit", {"workspace": ws, "message": "Over bob's lock", "paths": ["d.txt"]}, -32006) if "d.txt is locked by Bob Example" not in message: fail(f"the refusal says {message!r}") service.refused("lock", {"workspace": ws, "paths": ["d.txt"]}, -32006) service.refused("unlock", {"workspace": ws, "paths": ["d.txt"]}, -32006) step("alice's edit to d.txt is warned about; submit, lock and unlock are refused") released = service.call("unlock", {"workspace": ws, "paths": ["d.txt"], "force": True})["released"] if released != ["d.txt"] or "d.txt" in locks(): fail(f"force unlock released {released}") step("alice, the repository's owner, force-releases bob's lock") write(os.path.join(into, "a.txt"), "six\n") service.until("a.txt in changes", lambda: "a.txt" in changes()) service.call("submit", {"workspace": ws, "message": "Locked edits", "paths": ["a.txt", "d.txt"]}) done = service.finished(ws, "submit") if "released a.txt" not in done["message"] or locks(): fail(f"the submit did not release a.txt: {done['message']!r}, locks {locks()}") step(f"submit releases alice's lock ({done['message']})") # Lock on edit: a tracked binary file, and a text file beside it. with open(os.path.join(into, "art.bin"), "wb") as f: f.write(b"\x00\x01art") service.until("art.bin in changes", lambda: "art.bin" in changes()) service.call("submit", {"workspace": ws, "message": "Add art", "paths": ["art.bin"]}) service.finished(ws, "submit") settings = service.call("workspace_settings", {"workspace": ws, "lock_on_edit": True}) if not settings["lock_on_edit"]: fail(f"workspace_settings answered {settings}") with open(os.path.join(into, "art.bin"), "wb") as f: f.write(b"\x00\x02art") write(os.path.join(into, "e.txt"), "text edit\n") taken = service.until("the lock on art.bin", lambda: locks().get("art.bin")) if not taken["mine"] or "e.txt" in locks(): fail(f"lock on edit took {sorted(locks())}") service.call("submit", {"workspace": ws, "message": "Edit art", "paths": ["art.bin", "e.txt"]}) service.finished(ws, "submit") if locks(): fail(f"locks left after submitting art.bin: {sorted(locks())}") step("lock on edit locks the edited binary file, not the text file") # Autosync on change: bob's push arrives without a sync from alice. service.call("workspace_settings", {"workspace": ws, "autosync": "on_change", "lock_on_edit": False}) bob("sync") write(os.path.join(bob_wc, "c.txt"), "bob's art\n") bob("stage", "c.txt") bob("commit", "Bob updates c.txt") bob("push") service.until("autosync to bring c.txt", lambda: read(os.path.join(into, "c.txt")) == "bob's art\n") step("autosync pulls bob's push") # Overlapping edits: autosync holds back and warns; alice's edit stays. write(os.path.join(into, "c.txt"), "alice's art\n") service.until("c.txt in changes", lambda: "c.txt" in changes()) bob("sync") write(os.path.join(bob_wc, "c.txt"), "bob's second art\n") bob("stage", "c.txt") bob("commit", "Bob updates c.txt again") bob("push") service.notice("autosync held back: local edits to c.txt overlap remote changes") status = {w["id"]: w for w in service.call("status")["workspaces"]}[ws] if "c.txt" not in status["warning"] or not status["behind"]: fail(f"the workspace shows {status}") if read(os.path.join(into, "c.txt")) != "alice's art\n": fail("autosync overwrote alice's edit") step("autosync holds back over alice's overlapping edit, and says so") if __name__ == "__main__": main()