Files
claude-config/bin/record_store/confluence_page.py
T

130 lines
5.8 KiB
Python

"""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 is handed, the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12). The store keeps no version itself: its caller hands each write the version, as a Held's, and keeps the one the write leaves (lilleman, 2026-11-16)."""
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 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. A write needs both, so a Held's version holds both, as JSON."""
version: int
title: str
@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.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 = 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
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 Held(text, Seen(seen.version + 1, seen.title).token)
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"]))
except (ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}")