"""Mail and agent handles between two daemons after a move. The source daemon's PATH holds a loopback ssh, as in move_test, whose host `vassago` runs commands with ALBEDO_HOME set to the peer daemon's home and a login shell that reads no profile. The `down` switch makes every ssh fail as an unreachable host does (a laptop's peer asleep). There is no ssh the other way: the target never reaches the source, as with a laptop. A child of a session moves to vassago; its parent stays here. Letters go to it through the source's pusher, and its letters to "parent" come back through the long-poll the source keeps open. """ import json import shutil import sqlite3 import sys import tempfile import unittest from contextlib import closing from pathlib import Path from _transfer_support import ( drop_relays, finish_move, idle, loopback_ssh, settled_move, start_move, wait_for, ) from harness import ( Albedo, Provider, exclusive_class, fresh_prompt, operation_id, peer_daemon, python, text, ) ELSEWHERE = "which this daemon can't reach; ask from there" def rows(home, sql, *args): with closing(sqlite3.connect(Path(home) / "albedo.sqlite", timeout=10)) as db: return db.execute(sql, args).fetchall() class Forwarding(unittest.TestCase): """A parent here and its child moved to vassago, with what the tests need to drive both daemons. It has no tests of its own.""" remote_home: Path hosts: Path down: Path def setUp(self): self.addCleanup(self.recover) def prepare(app): loopback = loopback_ssh( app, Path(tempfile.mkdtemp(prefix="host-", dir=app.root)) ) self.remote_home = loopback.remote_home self.hosts = loopback.hosts self.down = loopback.down self.provider = Provider(lambda _request: text("done")) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) def target_prepare(peer): # The source's profile, with its key: the moved child runs there. for name in ("config.json", "creds.json"): if (self.app.home / name).exists(): shutil.copy(self.app.home / name, peer.home / name) self.target = peer_daemon("forward-target", prepare=target_prepare) (self.hosts / "vassago").write_text(str(self.target.home)) destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home)) self.parent = self.app.session() self.app.prompt(self.parent, "hello").close() self.app.idle(self.parent) self.child = operation_id() self.app.api( f"/sessions/{self.child}", { "kind": "child", "parent_id": self.parent, "address": "kid", "name": "kid", "initial_input_id": operation_id(), "task": "wait for letters", }, method="PUT", headers={"If-None-Match": "*"}, ).close() self.app.idle(self.child, timeout=60) self.app.idle(self.parent, timeout=60) transfer = operation_id() start_move(self.app, self.child, transfer, f"vassago:{destination}") move = settled_move(self.app, transfer, 90) self.assertEqual(move["state"], "checklist", move) self.assertEqual(finish_move(self.app, transfer)["state"], "active") def recover(self): self.down.unlink(missing_ok=True) def execute(self, daemon, session, source): """Runs one python cell in `session` on `daemon` (the app or the target) and answers the cell's tool result as text.""" marker = "forward cell " + operation_id() answer = self.provider.script def dispatch(request): if fresh_prompt(request) == marker: return python(source) return answer(request) self.provider.script = dispatch try: daemon.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": marker}, method="PUT", ).close() idle(daemon, session) finally: self.provider.script = answer with daemon.api(f"/sessions/{session}/history") as response: items = json.load(response)["items"] [cell] = [item for item in items if item["kind"] == "tool_result"][-1:] return json.dumps(cell) def arrived(self, home, recipient, body): return rows( home, "SELECT id,sender,sender_name,created_at FROM mail WHERE recipient=? AND body=?", recipient, body, ) # exclusive: the daemon's PATH holds the loopback ssh, and a test kills its # relays @exclusive_class class MoveForwardTests(Forwarding): def test_a_letter_to_a_moved_session_arrives_there_once(self): cell = self.execute( self.app, self.parent, f"r = await mail.submit({self.child!r}, 'hello over there')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(letter, sender, name, _)] = wait_for( lambda: self.arrived(self.target.home, self.child, "hello over there"), 30, "the letter never reached the target", ) # Its sender lives on the source: kept with where it lives. self.assertIsNone(sender) [(remote, host)] = rows( self.target.home, "SELECT sender,host FROM mail_remote WHERE letter=?", letter, ) self.assertEqual(remote, self.parent) self.assertTrue(host) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_outbox WHERE id=? AND delivered_at IS NOT NULL", letter, ), 30, "the source never settled the letter", ) # A resend (an ack the relay dropped) is taken again without a copy. with self.target.api( "/mail/forwarded", { "origin": "source", "host": host, "letters": [ { "id": letter, "recipient": self.child, "sender": self.parent, "sender_name": name, "kind": "message", "body": "hello over there", } ], }, ) as response: [ack] = json.load(response)["acks"] self.assertEqual(ack, {"id": letter, "error": None, "retry": False}) self.assertEqual( len(self.arrived(self.target.home, self.child, "hello over there")), 1 ) # And the moved child reads it there. idle(self.target, self.child) with self.target.api(f"/sessions/{self.child}/history") as response: self.assertIn("hello over there", response.read().decode()) def test_a_letter_waits_while_the_target_is_out_of_reach(self): self.down.touch() self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'while you were away')", ) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_peers WHERE unreachable_since IS NOT NULL", ), 60, "the source never found the target out of reach", ) cell = self.execute( self.app, self.parent, "print('AWAITING', [a['forwarding'] for a in (await mail.open())['awaiting']])", ) self.assertIn("AWAITING ['queued for vassago, unreachable since ", cell) self.assertEqual( self.arrived(self.target.home, self.child, "while you were away"), [] ) self.down.unlink() wait_for( lambda: self.arrived(self.target.home, self.child, "while you were away"), 60, "the letter never arrived once the target was back", ) def test_a_moved_child_writes_to_its_parent_here(self): self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'report back')" ) wait_for(lambda: self.arrived(self.target.home, self.child, "report back"), 30) idle(self.target, self.child) cell = self.execute( self.target, self.child, "import time\n" "sent = time.time()\n" "r = await mail.submit('parent', 'reporting from vassago')\n" "print('SENT', sent, r.status, r.forwarding)", ) self.assertIn("SENT", cell) sent = float(cell.split("SENT ", 1)[1].split(" ", 1)[0]) [(_, sender, _, created)] = wait_for( lambda: self.arrived(self.app.home, self.parent, "reporting from vassago"), 30, "the parent never got the letter", ) self.assertEqual(sender, self.child) latency = created / 1000 - sent print(f"collect latency {latency:.3f}s", file=sys.stderr) self.assertLess(latency, 5) # The answer closes the request on the side that opened it. idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell) # The long-poll survives its connection dying: the source opens it # again and the next letter still comes. drop_relays(self.remote_home) self.execute( self.target, self.child, "await mail.submit('parent', 'after the drop')" ) wait_for( lambda: self.arrived(self.app.home, self.parent, "after the drop"), 60, "the parent never got the letter sent after the connection dropped", ) def test_handles_reach_a_moved_session_and_not_the_other_way(self): cell = self.execute( self.app, self.parent, f"h = await agents.get({self.child!r})\n" "page = await h.messages()\n" "print('READ', 'wait for letters' in str(page))\n" "print('CANCELLED', await h.cancel())", ) self.assertIn("READ True", cell) self.assertIn("CANCELLED", cell) self.assertNotIn("Error", cell) cell = self.execute( self.target, self.child, "p = await agents.get('parent')\n" "try:\n" " await p.messages()\n" "except AgentsError as error:\n" " print('REFUSED', error)\n" "try:\n" " await p.cancel()\n" "except AgentsError as error:\n" " print('REFUSED', error)", ) self.assertEqual(cell.count(ELSEWHERE), 2, cell) if __name__ == "__main__": unittest.main()