210 lines
7.7 KiB
Python
210 lines
7.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Verifies the bug Joakim hit: after editing an EXISTING note through
|
|
hd-joe and quitting, the local .hd/notes/<id>.md cache (and thus what
|
|
`cat` on the symlink shows) must reflect the edit -- not just the server.
|
|
"""
|
|
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, content_hash, parse_current_tags, parse_frontmatter
|
|
|
|
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 CombinedFakeServer:
|
|
def __init__(self, port, initial_notes):
|
|
self.notes = initial_notes # id -> {"content", "time", "revision"}
|
|
self.port = port
|
|
self.lock = threading.Lock()
|
|
|
|
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
|
|
|
@self.sio.event
|
|
def connect(sid, environ, auth):
|
|
from urllib.parse import parse_qs
|
|
qs = parse_qs(environ.get("QUERY_STRING", ""))
|
|
note_id = (qs.get("noteId") or [None])[0]
|
|
with self.lock:
|
|
n = self.notes.get(note_id)
|
|
if n is None:
|
|
return
|
|
self.sio.save_session(sid, {"note_id": note_id})
|
|
self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid)
|
|
|
|
@self.sio.on("operation")
|
|
def on_operation(sid, base_revision, operation, selection):
|
|
with self.lock:
|
|
session = self.sio.get_session(sid)
|
|
note_id = session["note_id"]
|
|
n = self.notes[note_id]
|
|
if base_revision != n["revision"]:
|
|
return
|
|
try:
|
|
n["content"] = apply_operation_strict(n["content"], operation)
|
|
except Exception as exc:
|
|
print("[fake server] rejected:", exc, operation)
|
|
return
|
|
n["revision"] += 1
|
|
n["time"] += 1
|
|
self.sio.emit("ack", n["revision"], to=sid)
|
|
|
|
self._socketio_app = socketio.WSGIApp(self.sio)
|
|
|
|
def wsgi(environ, start_response):
|
|
request = Request(environ)
|
|
if request.path == "/history":
|
|
with self.lock:
|
|
history = []
|
|
for nid, n in self.notes.items():
|
|
fm = parse_frontmatter(n["content"])
|
|
import yaml
|
|
meta = yaml.safe_load(fm["yaml_str"]) or {} if fm else {}
|
|
tags = parse_current_tags(meta)
|
|
title = meta.get("title", nid)
|
|
history.append({"id": nid, "text": title, "tags": tags, "time": n["time"]})
|
|
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
|
return resp(environ, start_response)
|
|
if request.path.endswith("/download"):
|
|
nid = request.path.split("/")[1]
|
|
with self.lock:
|
|
n = self.notes.get(nid)
|
|
resp = Response(n["content"] if n else "", mimetype="text/markdown",
|
|
status=200 if n else 404)
|
|
return resp(environ, start_response)
|
|
return self._socketio_app(environ, start_response)
|
|
|
|
self.srv = make_server("127.0.0.1", port, wsgi, 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\nold content here"
|
|
server = CombinedFakeServer(port, {note_id: {"content": initial_content, "time": 1, "revision": 0}})
|
|
server.start()
|
|
time.sleep(0.2)
|
|
|
|
tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-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)
|
|
|
|
# Pre-populate state + cache as `hdc sync` would have, from an EARLIER sync
|
|
# (deliberately stale -- "old content here" -- to prove the refresh works).
|
|
from hd_core import NoteState
|
|
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
|
|
try:
|
|
log_path = "/tmp/hd-joe-cache-refresh.log"
|
|
sock_path = "/tmp/hd-joe-cache-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)
|
|
|
|
# Go to EOF and type -- mirrors Joakim's actual test.
|
|
child.send("\x0bv")
|
|
time.sleep(0.3)
|
|
child.send(" -- edited via hd-joe")
|
|
time.sleep(0.6)
|
|
|
|
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)
|
|
|
|
server_text = server.notes[note_id]["content"]
|
|
print("server content:", repr(server_text[-60:]))
|
|
ok &= "edited via hd-joe" in server_text
|
|
|
|
cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
|
print("local cache content:", repr(cache_text[-60:]))
|
|
ok &= cache_text == server_text
|
|
# We typed at EOF, so the original text is still there as a prefix --
|
|
# the bug this test guards against is the cache staying at the OLD
|
|
# revision entirely, not the old text being removed.
|
|
ok &= cache_text.startswith("---\ntitle: Masten")
|
|
|
|
symlink_text = (tag_dir / "Masten").read_text()
|
|
ok &= symlink_text == server_text
|
|
print("symlink (what 'cat' shows) matches server:", symlink_text == server_text)
|
|
|
|
reloaded_state = State.load(hd_dir)
|
|
expected_hash = content_hash(server_text)
|
|
hash_ok = reloaded_state.notes[note_id].content_hash == expected_hash
|
|
print("state.json content_hash updated:", hash_ok)
|
|
ok &= hash_ok
|
|
|
|
finally:
|
|
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())
|