173 lines
5.9 KiB
Python
173 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Verifies the follow-up to the cache-refresh fix: while hd-joe is still
|
|
open, an edit from ANOTHER client (webUI, in practice) should show up in
|
|
the local .hd/notes/<id>.md cache within about a second -- not only once
|
|
you quit. Throttled to at most once/second (see Agent.remote_operation),
|
|
so this waits past that window before checking.
|
|
"""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import socket as socketmod
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import pexpect
|
|
import socketio
|
|
from werkzeug.serving import make_server
|
|
from werkzeug.wrappers import Request, Response
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
|
from hd_client import apply_operation
|
|
from hd_core import Config, Cookies, State, NoteState, content_hash
|
|
|
|
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe")
|
|
AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py")
|
|
|
|
|
|
def apply_operation_strict(text, op):
|
|
for c in op:
|
|
if isinstance(c, bool):
|
|
raise ValueError(f"unknown operation: {c!r}")
|
|
if isinstance(c, int) and c == 0:
|
|
raise ValueError(f"unknown operation: {c!r}")
|
|
return apply_operation(text, op)
|
|
|
|
|
|
class FakeServer:
|
|
def __init__(self, port, initial_text):
|
|
self.text = initial_text
|
|
self.revision = 0
|
|
self.lock = threading.Lock()
|
|
|
|
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
|
|
|
@self.sio.event
|
|
def connect(sid, environ, auth):
|
|
with self.lock:
|
|
self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid)
|
|
|
|
@self.sio.on("operation")
|
|
def on_operation(sid, base_revision, operation, selection):
|
|
with self.lock:
|
|
if base_revision != self.revision:
|
|
return
|
|
try:
|
|
self.text = apply_operation_strict(self.text, operation)
|
|
except Exception as exc:
|
|
print("[fake server] rejected:", exc, operation)
|
|
return
|
|
self.revision += 1
|
|
self.sio.emit("ack", self.revision, to=sid)
|
|
self.sio.emit("operation", (sid, self.revision, operation, selection, None), skip_sid=sid)
|
|
|
|
self.app = socketio.WSGIApp(self.sio)
|
|
self.srv = make_server("127.0.0.1", port, self.app, threaded=True)
|
|
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
|
|
|
def start(self):
|
|
self.thread.start()
|
|
|
|
def stop(self):
|
|
self.srv.shutdown()
|
|
|
|
|
|
def free_port():
|
|
s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM)
|
|
s.bind(("127.0.0.1", 0))
|
|
port = s.getsockname()[1]
|
|
s.close()
|
|
return port
|
|
|
|
|
|
def main():
|
|
port = free_port()
|
|
note_id = "n1"
|
|
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nstarting content"
|
|
server = FakeServer(port, initial_content)
|
|
server.start()
|
|
time.sleep(0.2)
|
|
|
|
tmpdir = Path(tempfile.mkdtemp(prefix="hd-live-refresh-test-"))
|
|
root = tmpdir / "notes"
|
|
hd_dir = root / ".hd"
|
|
(hd_dir / "notes").mkdir(parents=True)
|
|
Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir)
|
|
Cookies(header="session=1").save(hd_dir)
|
|
|
|
state = State()
|
|
(hd_dir / "notes" / f"{note_id}.md").write_text(initial_content)
|
|
state.notes[note_id] = NoteState(
|
|
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
|
|
content_hash=content_hash(initial_content), last_seen_time=1,
|
|
)
|
|
state.save(hd_dir)
|
|
tag_dir = root / "sl6cv"
|
|
tag_dir.mkdir(parents=True)
|
|
(tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md")
|
|
|
|
ok = True
|
|
child = None
|
|
try:
|
|
log_path = "/tmp/hd-joe-live-refresh.log"
|
|
sock_path = "/tmp/hd-joe-live-refresh.sock"
|
|
for p in (log_path, sock_path):
|
|
try:
|
|
os.remove(p)
|
|
except OSError:
|
|
pass
|
|
cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug'
|
|
child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"},
|
|
dimensions=(24, 80), timeout=10)
|
|
time.sleep(1.0) # let hd-joe connect and settle
|
|
|
|
cache_before = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
|
ok &= "starting content" in cache_before
|
|
ok &= "REMOTE EDIT" not in cache_before
|
|
print("cache before remote edit:", repr(cache_before[-40:]))
|
|
|
|
# A second connection -- standing in for webUI -- edits the SAME note
|
|
# while hd-joe is still open.
|
|
remote = socketio.Client()
|
|
remote.connect(f"http://127.0.0.1:{port}/?noteId={note_id}", socketio_path="socket.io",
|
|
transports=["websocket", "polling"])
|
|
time.sleep(0.3)
|
|
op = [len(initial_content), " -- REMOTE EDIT"]
|
|
remote.emit("operation", (0, op, {"ranges": []}))
|
|
time.sleep(1.5) # past the 1s throttle window
|
|
|
|
# Check the cache WHILE hd-joe is STILL RUNNING -- this is the point
|
|
# of the test. Don't quit yet.
|
|
cache_during = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
|
print("cache while hd-joe still open:", repr(cache_during[-40:]))
|
|
ok &= "REMOTE EDIT" in cache_during
|
|
|
|
remote.disconnect()
|
|
|
|
child.send("\x0bx")
|
|
time.sleep(0.4)
|
|
child.send("\r")
|
|
try:
|
|
child.wait()
|
|
except pexpect.TIMEOUT:
|
|
pass
|
|
if child.isalive():
|
|
child.terminate(force=True)
|
|
time.sleep(0.3)
|
|
|
|
finally:
|
|
if child and child.isalive():
|
|
child.terminate(force=True)
|
|
server.stop()
|
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
|
|
print("\nPASS" if ok else "\nFAIL")
|
|
return 0 if ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|