"""A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim. A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12).""" import dataclasses import json import pathlib import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown from rest_client.json_request import ErrorAnswer from failure import Failure from project_config.settings import Page from text_files.file_writes import replace_file # What Confluence answers to a write whose version isn't the one after the version it holds. CONFLICT = 409 SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents" @dataclasses.dataclass(frozen=True) class Seen: """The page's version number and title as the store last read or wrote them. A write needs both.""" version: int title: str @dataclasses.dataclass class ConfluencePage: """The text of page as markdown, read and written with the credentials env_file holds. kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory.""" page: Page env_file: pathlib.Path kept: pathlib.Path | None = None http: Http = confluence_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf seen: Seen | None = None @property def label(self) -> str: return self.page.spelling @property def tracked(self) -> str | None: return None @property def url(self) -> str: return f"{self.page.site}/wiki/api/v2/pages/{self.page.page_id}" def read(self) -> str | Failure: """The page's text as markdown; empty where the page is.""" answer = self.fetched("?body-format=atlas_doc_format") if isinstance(answer, Failure): return answer seen, held = answer if not isinstance(held, str): return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format") text = self.converted(held) if isinstance(text, Failure): return text # Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw. unkept = self.keep(seen) return unkept or text def converted(self, held: str) -> str | Failure: """The markdown of the body held, the JSON of an ADF document; empty where held is.""" if not held: return "" try: document = json.loads(held) except ValueError: return Failure(f"{self.label} holds a body that is not JSON") texts = self.to_markdown([document]) if isinstance(texts, Refused): return Failure(f"{self.label}: {texts.failure.reason}") if isinstance(texts, Failure): return Failure(f"cannot convert {self.label} to markdown: {texts.reason}") return texts[0] def write(self, text: str) -> Failure | None: """Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands.""" seen = self.seen or self.recalled() if seen is None: fetched = self.fetched("") if isinstance(fetched, Failure): return fetched seen = fetched[0] if isinstance(seen, Failure): return seen document = self.to_adf(text) if isinstance(document, Failure): return Failure(f"cannot convert the text for {self.label} to ADF: {document.reason}") authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization body = {"id": self.page.page_id, "status": "current", "title": seen.title, "body": {"representation": "atlas_doc_format", "value": json.dumps(document)}, "version": {"number": seen.version + 1}} answer = self.http("PUT", self.url, authorization, body) if isinstance(answer, ErrorAnswer) and answer.status == CONFLICT: return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})") if isinstance(answer, Failure): return Failure(f"cannot write {self.label}: {answer.reason}") return self.keep(Seen(seen.version + 1, seen.title)) def fetched(self, query: str) -> tuple[Seen, object] | Failure: """The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't.""" authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization answer = self.http("GET", self.url + query, authorization, None) if isinstance(answer, Failure): return Failure(f"cannot read {self.label}: {answer.reason}") page = answer if isinstance(answer, dict) else {} version, title = page.get("version"), page.get("title") number = version.get("number") if isinstance(version, dict) else None if not isinstance(number, int) or not isinstance(title, str): return Failure(f"{self.label} is {SHAPE}: its version number or title is missing") body = page.get("body") adf = body.get("atlas_doc_format") if isinstance(body, dict) else None return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None def keep(self, seen: Seen) -> Failure | None: self.seen = seen if self.kept is None: return None try: self.kept.parent.mkdir(parents=True, exist_ok=True) except OSError as failure: return Failure(f"cannot write {self.kept}: {failure.strerror}") unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode()) return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None def recalled(self) -> Seen | Failure | None: """The version and title the file kept holds; None where kept is None or names no file.""" if self.kept is None: return None try: held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8")) return Seen(int(held["version"]), str(held["title"])) except FileNotFoundError: return None except (OSError, ValueError, KeyError, TypeError) as failure: return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}")