"""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 after the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12).""" import dataclasses import hashlib 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 record_store.held import Held from project_config.settings import Page # 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 a read found them or a write left them, and the digest of the markdown it found or sent. A write needs the version and title, and sends nothing where its text has that digest, so a Held's version holds all three, as JSON. The digest is None where the version came from a request that held no text.""" version: int title: str digest: str | None = None @property def token(self) -> str: return json.dumps(dataclasses.asdict(self)) @dataclasses.dataclass class ConfluencePage: """The text of page as markdown, read and written with the credentials env_file holds.""" page: Page env_file: pathlib.Path http: Http = confluence_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf @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.""" held = self.held() return held if isinstance(held, Failure) else held.text def held(self) -> Held | Failure: """The page's text as markdown, with its version and title as the version a write over it names.""" answer = self.fetched("?body-format=atlas_doc_format") if isinstance(answer, Failure): return answer seen, body = answer if not isinstance(body, str): return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format") text = self.converted(body) return text if isinstance(text, Failure) else Held(text, Seen(seen.version, seen.title, digest_of(text)).token) 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, over: str | None) -> Held | Failure: """Replaces the page's text with text, as the version after over, the one held() gave. Where over is None, it replaces the page as it stands.""" seen = self.seen_of(over) if isinstance(seen, Failure): return seen # A read's markdown leaves out the localIds and spacing paragraphs Confluence holds, so a write of the same text back would drop them: send nothing. Without a write Confluence answers no 409, so read the version to refuse where a teammate saved since. if over is not None and seen.digest == digest_of(text): current = self.fetched("") if isinstance(current, Failure): return current if current[0].version != seen.version: return self.saved_since(seen.version, f"Confluence holds version {current[0].version}") return Held(text, over) 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 self.saved_since(seen.version, answer.reason) if isinstance(answer, Failure): return Failure(f"cannot write {self.label}: {answer.reason}") return Held(text, Seen(seen.version + 1, seen.title, digest_of(text)).token) def saved_since(self, version: int, evidence: str) -> Failure: """The refusal of a write over version, which a teammate's save replaced, as evidence shows.""" return Failure(f"someone saved {self.label} since the loop read version {version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({evidence})") 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 seen_of(self, over: str | None) -> Seen | Failure: """The version and title a write sends: those over holds, else the page's as it stands.""" if over is None: fetched = self.fetched("") return fetched if isinstance(fetched, Failure) else fetched[0] try: held: typing.Any = json.loads(over) return Seen(int(held["version"]), str(held["title"]), held.get("digest")) except (ValueError, KeyError, TypeError) as failure: return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}") def digest_of(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()