Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(google_docs): read back a person's edits of a declared doc (#2866)

Jiangzhoua665b8ff58ad
diff --git a/dev/google_docs_real_account_check.py b/dev/google_docs_real_account_check.py
index d1db6a11..9c67e123 100644
--- a/dev/google_docs_real_account_check.py
+++ b/dev/google_docs_real_account_check.py
@@ -12,10 +12,17 @@ another; then it changes a third section and checks:
1. the doc it created reads back as exactly what was declared (nothing left
to write), which is what makes "a person's edit" detectable at all;
2. a rerun with unchanged content makes no request to Google;
-3. a change to one section rewrites that section only: the commented section
+3. ``read_doc`` hands back your edit of Gamma, and a memoized reader runs
+ again for it but not for the target's own writes;
+4. a change to one section rewrites that section only: the commented section
keeps its text, and the comment is still there, quoting the same text;
-4. the section you edited keeps your text, and the run warns about it;
-5. dropping the declaration moves the doc to the trash (not deleted for good).
+5. the section you edited keeps your text, and the run warns about it;
+6. declaring what ``read_doc`` returned takes your edit in, without rewriting it;
+7. dropping the declaration moves the doc to the trash (not deleted for good).
+
+It also reports whether stamping the doc's Drive appProperties leaves its
+Docs revision where the write left it, which keeps a reader's validation to
+two requests.
The state database lives in a temporary directory, so every run starts fresh.
"""
@@ -78,6 +85,14 @@ class _Counting:
return getattr(self._inner, name)
+_watch_runs: list[google_docs.DocRead | None] = []
+
+
+async def _watch(name: str, declared: str) -> None:
+ _watch_runs.append(await google_docs.read_doc(GDOCS, name, declared))
+
+
def _pause(prompt: str) -> None:
input(f"\n{prompt}\nPress Enter when done. ")
@@ -133,6 +148,34 @@ def main() -> int:
)
app.update_blocking()
+
+ @coco.fn
+ async def watch_main() -> None:
+ await coco.use_mount(coco.component_subpath("watch"), _watch, name, V1)
+
+ watcher = coco.App(
+ coco.AppConfig(name="GoogleDocsRealAccountWatch", environment=env),
+ watch_main,
+ )
+
+ def watch() -> int:
+ before = len(_watch_runs)
+ watcher.update_blocking()
+ return len(_watch_runs) - before
+
+ def read_back(declared: str) -> google_docs.DocRead | None:
+ out: list[google_docs.DocRead | None] = []
+
+ @coco.fn
+ async def read_main() -> None:
+ out.append(await google_docs.read_doc(GDOCS, name, declared))
+
+ coco.App(
+ coco.AppConfig(name="GoogleDocsRealAccountRead", environment=env),
+ read_main,
+ ).update_blocking()
+ return out[0]
+
google = _target._Google(account)
files = (
google._drive.files()
@@ -158,6 +201,9 @@ def main() -> int:
app.update_blocking()
check("an unchanged rerun makes no request", _Counting.count == 0)
+ check("a reader reads the doc", watch() == 1 and _watch_runs[-1] is not None)
+ check("an unchanged doc does not run the reader again", watch() == 0)
+
_pause(
f"In the doc, add a comment on the sentence {COMMENTED!r} (section "
"Beta), and change one word in the Gamma sentence. Leave Alpha alone."
@@ -177,8 +223,26 @@ def main() -> int:
print("No comment found on the doc; add one and run the check again.")
return 1
+ gamma = ("CocoIndex real-account check", "Gamma")
+ check("your edit runs the reader again", watch() == 1)
+ seen = _watch_runs[-1]
+ check(
+ "read_doc names Gamma as edited, and nothing as deleted",
+ seen is not None and seen.edited == (gamma,) and seen.deleted == (),
+ )
+ if seen is not None:
+ print(" read back:", [ln for ln in seen.content.splitlines() if ln][-1])
+ check("read_doc gives the doc's link", seen.url == _target.doc_url(doc_id))
+
content["content"] = V2
app.update_blocking()
+ found = google.find(_target.tag_of(GDOCS.key, name))
+ stamp = found.stamp if found is not None else None
+ check(
+ "(cost) stamping the doc leaves its Docs revision where the write left it",
+ stamp is not None and _target.short(google.revision(doc_id)) == stamp.after,
+ )
+ check("the target's own write does not run the reader again", watch() == 0)
after = _docs.read_document(google.get(doc_id))
alpha_text = [p.text for p in after.content(after.ranges[blocks[1].block_id])]
check("Alpha was rewritten", "The alpha section, version two." in alpha_text)
@@ -219,6 +283,23 @@ def main() -> int:
_yes("Look at the doc: is the comment still on its sentence in Beta?"),
)
+ taken = read_back(V2)
+ gamma_before = after.content(after.ranges[blocks[3].block_id])
+ warnings.clear()
+ if taken is not None:
+ content["content"] = taken.content
+ app.update_blocking()
+ adopted = _docs.read_document(google.get(doc_id))
+ check(
+ "declaring what read_doc returned takes your edit in, unchanged",
+ taken is not None
+ and not any("Gamma" in w for w in warnings)
+ and adopted.content(adopted.ranges[blocks[3].block_id]) == gamma_before
+ and adopted.ranges[blocks[3].block_id].written
+ == _markdown.fingerprint(gamma_before),
+ )
+ check("taking your edit in does not run the reader again", watch() == 0)
+
content["content"] = None
app.update_blocking()
trashed = (
diff --git a/docs/src/content/docs/connectors/google_docs.mdx b/docs/src/content/docs/connectors/google_docs.mdx
index f06eed70..1b915847 100644
--- a/docs/src/content/docs/connectors/google_docs.mdx
+++ b/docs/src/content/docs/connectors/google_docs.mdx
@@ -6,10 +6,10 @@ rust_counterpart: connectors
description: >
Keep a Google Doc in step with Markdown your flow declares. The doc is
updated in place, block by block, so unchanged paragraphs and the comments
- on them stay; a person's edits are kept and reported. Signs in with the
- drive.file scope only.
+ on them stay; a person's edits are kept and reported, and can be read back
+ as Markdown. Signs in with the drive.file scope only.
---
-The `google_docs` connector keeps a Google Doc in step with Markdown your flow declares: a report, a brief, a summary that people read and comment on in Google Docs. It creates the doc on the first run and, on each change, rewrites only the parts whose content changed.
+The `google_docs` connector keeps a Google Doc in step with Markdown your flow declares: a report, a brief, a summary that people read and comment on in Google Docs. It creates the doc on the first run and, on each change, rewrites only the parts whose content changed. What people change in the doc can be read back, so a flow can take their edits in.
```python
from cocoindex.connectors import google_docs
@@ -87,10 +87,12 @@ def declare_doc(account: ContextKey[UserAccount], name: str, content: str) -> No
Declares a Google Doc whose content is `content`, in Markdown.
- `account` is the [`ContextKey`](../programming_guide/context) under which the app's lifespan provides the signed-in `UserAccount`.
-- `name` is the doc's title when it is created, and, with the context key's name, its identity across runs.
+- `name` is the doc's title when it is created, and, with the context key's name, its identity.
- `content` is Markdown; see [Markdown](#markdown).
-On the first run, the target creates the doc in your My Drive and tags it with an id it keeps in its own state. From then on it finds the doc by that tag, not by its name: rename the doc or move it to another folder, and the target keeps writing to it. Changing `name` in your code declares a different doc: the old one is trashed and a new one created.
+On the first run, the target creates the doc in your My Drive and tags it with an id made from the context key's name and `name`. From then on it finds the doc by that tag, not by its title: rename the doc or move it to another folder, and the target keeps writing to it. Changing `name` in your code declares a different doc: the old one is trashed and a new one created.
+
+The tag depends on the declaration alone, as a table's name does for a database target. A run that starts with a new state (on another machine, or after deleting the state database) finds the doc and keeps writing to it, and two apps that declare the same `name` under the same context key name with the same account write the same doc.
```python
from typing import AsyncIterator
@@ -133,14 +135,56 @@ People can edit the doc. A block a person changed since the target last wrote it
- A block a person deleted as a whole stays deleted, and is reported the same way.
- A block the flow no longer declares, but that a person edited, is left in the doc with the person's text, and the target lets go of it.
-A change of formatting counts as an edit as well, since the target compares the text with its bold, italic, code and links. Text a person adds between blocks belongs to no block, and the target leaves it alone.
+A change of formatting counts as an edit as well, since the target compares the text with its bold, italic, code and links. Whitespace does not: an empty paragraph, a space at either end of a paragraph, or bold that takes in the space after a word. Text a person adds between blocks belongs to no block, and the target leaves it alone.
+
+When a person renames a heading and the flow's version takes the new name in, the target keeps the block where it is, under its new name, rather than writing it again (the blocks under the heading, whose heading paths changed with it, too).
### Deleting the declaration
-When the declaration goes away (the code no longer declares the doc, or the app is dropped), the target moves the doc to the **trash**. It never deletes a doc permanently: Google Drive keeps a trashed file for 30 days, and you can restore it from there. A doc restored from the trash is not the target's again; the next declaration with the same `name` creates a new doc.
+When the declaration goes away (the code no longer declares the doc, or the app is dropped), the target moves the doc to the **trash**. It never deletes a doc permanently: Google Drive keeps a trashed file for 30 days, and you can restore it from there. Restored before the next declaration with the same `name`, the doc is the target's again; restored after it, it is not, since that declaration created a new doc, and the newer one stays the target's.
If a person moves the doc to the trash while it is still declared, the next change creates a new doc with the full content.
+### Reading back a person's edits
+
+```python
+async def read_doc(
+ account: ContextKey[UserAccount], name: str, declared: str
+) -> DocRead | None
+
+@dataclass(frozen=True)
+class DocRead:
+ url: str
+ content: str
+ edited: tuple[tuple[str, ...], ...]
+ deleted: tuple[tuple[str, ...], ...]
+```
+
+`read_doc` reads back the doc that `declare_doc(account, name, ...)` keeps, and returns `None` when there is none (not created yet, or in the trash). `declared` is the Markdown the doc was last declared with: the content of the run that last wrote it.
+
+- `url` is the doc's link.
+- `content` is `declared`, with each block a person edited in the doc replaced by the person's text, in Markdown, and each block a person deleted left out. The rest is `declared` exactly, so `content == declared` when no one changed a block. Declaring `content` takes the person's edits in: those blocks are the target's again, and their text is not rewritten.
+- `edited` and `deleted` are the heading paths of those blocks, as declared, in order: `("Brief", "Risks")` for the block under `## Risks` under `# Brief`, and `()` for the text before the first heading.
+
+It tells a person's edit from the target's own writes the same way the target does, by the [named ranges](#how-a-change-is-written).
+
+```python
+async def app_main() -> None:
+ report = await write_report() # Markdown
+ last = coco.use_state("brief", initial_value=None) # what the doc was declared with
+ if last.value is not None:
+ doc = await google_docs.read_doc(GDOCS, "Weekly brief", last.value)
+ if doc is not None and doc.content != last.value:
+ print(f"People edited {doc.edited} and deleted {doc.deleted} in {doc.url}")
+ google_docs.declare_doc(GDOCS, "Weekly brief", report)
+ last.value = report
+```
+
+A read is a data dependency of the function that made it, as a read of a file is. A memoized function that called `read_doc` runs again when a person edits or deletes a block of the doc, or the doc goes to the trash or is replaced, and is reused otherwise. The target's own writes do not make it run again: after each write the target stamps the doc with the revision it wrote, so that the next run can tell its write from a person's. Neither does a comment. Checking the record costs one Drive and one Docs request per run, and one more read of the doc when the doc's revision moved for another reason than the target's write. In a [preview](../programming_guide/app#previewing-an-update), `read_doc` reads the doc too.
+
+A person's text comes back in the [Markdown](#markdown) below, which parses back to what the doc holds. What the subset cannot spell (a style other than a heading, such as Title; a list item two levels deeper than the one above it) reads back otherwise, and the block stays the person's after `content` is declared.
+
### Markdown
The target writes the subset of Markdown a report needs:
@@ -156,4 +200,4 @@ The target writes the subset of Markdown a report needs:
| `[text](url)`, `<url>`, bare `http://` and `https://` URLs | Link |
| Fenced code blocks | One Roboto Mono paragraph per line |
-Anything else (a table, a numbered list, a block quote) is written as the text it is. A horizontal rule is dropped.
+Anything else (a table, a numbered list, a block quote) is written as the text it is. A horizontal rule is dropped. A backslash before any ASCII punctuation character writes that character as it is (`\*`, `\#`, `\[`).
diff --git a/python/cocoindex/connectors/google_docs/__init__.py b/python/cocoindex/connectors/google_docs/__init__.py
index f7c37ad2..00e23cae 100644
--- a/python/cocoindex/connectors/google_docs/__init__.py
+++ b/python/cocoindex/connectors/google_docs/__init__.py
@@ -2,11 +2,18 @@
# extra to install before anything imports the Google Drive connector.
from . import _target
from . import _auth
+from . import _reader
from ._target import *
from ._auth import *
+from ._reader import *
from cocoindex.connectors.google_drive._oauth import SignInError as SignInError
from cocoindex.connectors.google_drive._oauth import (
SignInRequiredError as SignInRequiredError,
)
-__all__ = _target.__all__ + _auth.__all__ + ["SignInError", "SignInRequiredError"]
+__all__ = (
+ _target.__all__
+ + _reader.__all__
+ + _auth.__all__
+ + ["SignInError", "SignInRequiredError"]
+)
diff --git a/python/cocoindex/connectors/google_docs/_docs.py b/python/cocoindex/connectors/google_docs/_docs.py
index 5fda45db..4a01a35e 100644
--- a/python/cocoindex/connectors/google_docs/_docs.py
+++ b/python/cocoindex/connectors/google_docs/_docs.py
@@ -24,9 +24,11 @@ Positions are UTF-16 code units, as the Docs API counts them.
from __future__ import annotations
import bisect
+import hashlib
+import json
import re
from collections.abc import Mapping, Sequence
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from typing import Any, Literal, NamedTuple
from ._markdown import (
@@ -37,6 +39,7 @@ from ._markdown import (
Run,
fingerprint,
merge_runs,
+ normalized,
)
RANGE_PREFIX = "cocoindex:"
@@ -259,6 +262,75 @@ def read_document(document: Mapping[str, Any]) -> DocState:
)
+def classify(
+ state: DocState, rng: OurRange, declared_fp: str
+) -> Literal["same", "update", "kept"]:
+ """What the block in ``rng`` is, against the declared version ``declared_fp``.
+
+ ``same``: the doc has the declared version (written by the target, or
+ typed by a person). ``update``: it has what the target last wrote, and the
+ declaration changed. ``kept``: a person changed it since the target wrote
+ it, to something other than the declared version.
+ """
+ current = fingerprint(state.content(rng))
+ whole = state.whole(rng)
+ if whole and current == declared_fp:
+ return "same"
+ if whole and current == rng.written:
+ return "update"
+ return "kept"
+
+
+def observe(state: DocState) -> str:
+ """A digest of what a person can change in the target's blocks: which are
+ there, and the text of each one edited since the target wrote it. Neither a
+ comment nor text outside every block changes it."""
+ seen = []
+ for block_id, rng in sorted(state.ranges.items()):
+ current = fingerprint(state.content(rng))
+ edited = not state.whole(rng) or current != rng.written
+ seen.append([block_id, current if edited else ""])
+ payload = json.dumps(seen, separators=(",", ":"))
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def _adopt_renamed(
+ state: DocState, blocks: Sequence[Block], written_blocks: frozenset[str] | None
+) -> tuple[DocState, frozenset[str]]:
+ """``state`` with each declared block that the doc has under another block's
+ range taken as that range, and those blocks: a person renamed a heading
+ (which renames the blocks under it), and the declaration took the new name
+ in. The range is recreated under the new name rather than its text
+ written again."""
+ declared = {block.block_id for block in blocks}
+ loose: dict[str, list[OurRange]] = {} # by current fingerprint, in doc order
+ for rng in sorted(state.ranges.values(), key=lambda r: r.start):
+ if rng.block_id not in declared and state.whole(rng):
+ loose.setdefault(fingerprint(state.content(rng)), []).append(rng)
+ if not loose:
+ return state, frozenset()
+ ranges = dict(state.ranges)
+ adopted: set[str] = set()
+ for block in blocks:
+ if block.block_id in ranges or (
+ written_blocks is not None and block.block_id in written_blocks
+ ):
+ continue
+ candidates = loose.get(fingerprint(block.paragraphs))
+ if not candidates:
+ continue
+ rng = candidates.pop(0)
+ del ranges[rng.block_id]
+ ranges[block.block_id] = replace(rng, block_id=block.block_id)
+ adopted.add(block.block_id)
+ if not adopted:
+ return state, frozenset()
+ renamed = DocState(
+ state.revision_id, state.paragraphs, ranges, state.stray_range_ids
+ )
+ return renamed, frozenset(adopted)
+
+
# --- planning --------------------------------------------------------------------
@@ -383,6 +455,7 @@ def plan_write(
edits: list[PersonEdit] = []
declared = {block.block_id: block for block in blocks}
new_fps = {block.block_id: fingerprint(block.paragraphs) for block in blocks}
+ state, adopted = _adopt_renamed(state, blocks, written_blocks)
# What each declared block is now.
status: dict[str, _Status] = {}
@@ -396,20 +469,13 @@ def plan_write(
else:
status[block.block_id] = "new"
continue
- current = fingerprint(state.content(rng))
- if not state.whole(rng) or current != rng.written:
- if current == new_fp and state.whole(rng):
- # The person wrote what the flow now says: the block is ours again.
- status[block.block_id] = "same"
- continue
- status[block.block_id] = "kept"
+ # "same" covers a person who wrote what the flow now says: the block
+ # is the target's again.
+ status[block.block_id] = classify(state, rng, new_fp)
+ if status[block.block_id] == "kept":
edits.append(
PersonEdit(block.label, "edited", withheld=new_fp != rng.written)
)
- elif current == new_fp:
- status[block.block_id] = "same"
- else:
- status[block.block_id] = "update"
# Blocks that keep their place: the most already in the declared order. A
# block a person edited never moves, so the order is chosen around those
@@ -485,7 +551,10 @@ def plan_write(
continue
pending = None
if kind == "same":
- if state.ranges[block_id].written != new_fps[block_id]:
+ # A range taken from a renamed block is named for that block.
+ if state.ranges[block_id].written != new_fps[block_id] or (
+ block_id in adopted
+ ):
touched.add(block_id)
seq += len(block.paragraphs)
elif kind == "update":
@@ -591,9 +660,11 @@ def _diff_block(
"""Plan the paragraphs of a changed block that changed; the next ``seq``."""
rng = state.ranges[block.block_id]
old = state.overlapping(rng.start, rng.end)
- old_paragraphs = [p.clipped(rng.start, rng.end) for p in old]
+ # Compared as edits are told from noise, so a paragraph a person retyped
+ # the same (a trailing space) is not rewritten.
+ old_paragraphs = [normalized(p.clipped(rng.start, rng.end)) for p in old]
new = block.paragraphs
- pairs = _lcs(old_paragraphs, new) + [(len(old), len(new))]
+ pairs = _lcs(old_paragraphs, [normalized(p) for p in new]) + [(len(old), len(new))]
i = j = 0
for next_i, next_j in pairs:
removed, added = old[i:next_i], new[j:next_j]
diff --git a/python/cocoindex/connectors/google_docs/_markdown.py b/python/cocoindex/connectors/google_docs/_markdown.py
index 54047520..dad200ff 100644
--- a/python/cocoindex/connectors/google_docs/_markdown.py
+++ b/python/cocoindex/connectors/google_docs/_markdown.py
@@ -13,6 +13,8 @@ headings that leads to it.
Paragraphs are the same model the target reads back from a document
(``_docs.py``), so what was written and what is there compare as equals.
+``render`` goes the other way, from paragraphs read back to Markdown that
+parses to the same paragraphs: how a person's text in the doc is handed back.
"""
from __future__ import annotations
@@ -20,7 +22,9 @@ from __future__ import annotations
import hashlib
import json
import re
+import string
from dataclasses import dataclass
+from typing import NamedTuple
# The font that marks inline code, written and read back.
CODE_FONT = "Roboto Mono"
@@ -107,19 +111,62 @@ def merge_runs(runs: list[Run]) -> tuple[Run, ...]:
return tuple(merged)
+def normalized(paragraph: Paragraph) -> Paragraph:
+ """The paragraph as edits are told from noise: what Markdown cannot spell
+ taken out, so a person's text and the same text written back compare equal.
+
+ Whitespace at the paragraph's ends is dropped, and whitespace at the ends of
+ a bold or italic run loses that style (``**`` and ``*`` cannot open or close
+ next to a space).
+ """
+ runs: list[Run] = []
+ for run in paragraph.runs:
+ if not (run.bold or run.italic):
+ runs.append(run)
+ continue
+ core = run.text.strip()
+ if not core:
+ runs.append(Run(run.text, False, False, run.code, run.link))
+ continue
+ lead = run.text[: len(run.text) - len(run.text.lstrip())]
+ trail = run.text[len(run.text.rstrip()) :]
+ if lead:
+ runs.append(Run(lead, False, False, run.code, run.link))
+ runs.append(Run(core, run.bold, run.italic, run.code, run.link))
+ if trail:
+ runs.append(Run(trail, False, False, run.code, run.link))
+ while runs and not runs[0].text.lstrip():
+ runs.pop(0)
+ while runs and not runs[-1].text.rstrip():
+ runs.pop()
+ if runs:
+ first = runs[0]
+ runs[0] = Run(
+ first.text.lstrip(), first.bold, first.italic, first.code, first.link
+ )
+ last = runs[-1]
+ runs[-1] = Run(last.text.rstrip(), last.bold, last.italic, last.code, last.link)
+ return Paragraph(paragraph.style, paragraph.bullet, merge_runs(runs))
+
+
def fingerprint(paragraphs: tuple[Paragraph, ...] | list[Paragraph]) -> str:
- """A short, stable digest of paragraphs, as they would read back from Docs."""
- payload = json.dumps(
- [p.canonical() for p in paragraphs], ensure_ascii=False, separators=(",", ":")
- )
+ """A short, stable digest of paragraphs, as they would read back from Docs.
+
+ Paragraphs are compared ``normalized``, and an empty one is left out: a
+ person pressing Enter twice has not edited the block.
+ """
+ canonical = [n.canonical() for n in (normalized(p) for p in paragraphs) if n.runs]
+ payload = json.dumps(canonical, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
# --- inline ------------------------------------------------------------------
-_ESCAPABLE = set("\\`*_{}[]()#+-.!<>|~")
+# Any ASCII punctuation can be escaped with a backslash, as in CommonMark.
+_ESCAPABLE = set(string.punctuation)
_LINK = re.compile(
- r"\[((?:[^\[\]\\]|\\.)*)\]" # [text]
+ # [text], where a code span may hold brackets
+ r"\[((?:[^\[\]\\`]|\\.|`[^`]*`|``(?:[^`]|`(?!`))*``)*)\]"
r"\(\s*<?((?:[^\s()<>]|\([^\s()<>]*\))+)>?" # (url, with balanced parentheses
r"(?:\s+\"[^\"]*\")?\s*\)" # and an optional "title")
)
@@ -139,14 +186,50 @@ class _Style:
return Run(text, self.bold, self.italic, self.code, self.link)
+def _escaped(text: str, index: int) -> bool:
+ """Whether ``text[index]`` follows an odd number of backslashes."""
+ count = 0
+ while index - count - 1 >= 0 and text[index - count - 1] == "\\":
+ count += 1
+ return count % 2 == 1
+
+
+def _code_spans(text: str, start: int) -> list[tuple[int, int]]:
+ """The code spans from ``start`` on, as ``parse_inline`` reads them."""
+ spans: list[tuple[int, int]] = []
+ i = start
+ while True:
+ i = text.find("`", i)
+ if i < 0:
+ return spans
+ if _escaped(text, i):
+ i += 1
+ continue
+ ticks = len(text[i:]) - len(text[i:].lstrip("`"))
+ end = text.find("`" * ticks, i + ticks)
+ if end < 0:
+ i += ticks
+ continue
+ spans.append((i, end + ticks))
+ i = end + ticks
+
+
def _closing(text: str, marker: str, start: int) -> int:
- """Where the emphasis opened before ``start`` closes, or -1."""
+ """Where the emphasis opened before ``start`` closes, or -1.
+
+ A marker that is escaped, or inside a code span, closes nothing.
+ """
+ code = _code_spans(text, start)
position = start
while True:
found = text.find(marker, position)
if found < 0:
return -1
- if text[found - 1] == "\\":
+ inside = next((hi for lo, hi in code if lo <= found < hi), None)
+ if inside is not None:
+ position = inside
+ continue
+ if _escaped(text, found):
position = found + 1
continue
if found == start or text[found - 1].isspace():
@@ -281,30 +364,38 @@ def _paragraph(style: str, bullet: int | None, text: str) -> Paragraph:
def parse(markdown: str) -> list[Paragraph]:
"""The paragraphs of ``markdown``, in order; blank paragraphs dropped outside code."""
- paragraphs: list[Paragraph] = []
- lines = markdown.replace("\r\n", "\n").replace("\r", "\n").split("\n")
- # The paragraph being gathered: (bullet level or None, lines so far).
- pending: tuple[int | None, list[str]] | None = None
+ return [paragraph for _, paragraph in _parse_lines(markdown)]
+
+
+def _lines(markdown: str) -> list[str]:
+ return markdown.replace("\r\n", "\n").replace("\r", "\n").split("\n")
+
+
+def _parse_lines(markdown: str) -> list[tuple[int, Paragraph]]:
+ """The paragraphs of ``markdown``, each with the index of its first line."""
+ paragraphs: list[tuple[int, Paragraph]] = []
+ # The paragraph being gathered: (first line, bullet level or None, lines so far).
+ pending: tuple[int, int | None, list[str]] | None = None
list_indents: list[int] = []
fence: str | None = None
def flush() -> None:
nonlocal pending
if pending is not None:
- level, parts = pending
+ first, level, parts = pending
paragraph = _paragraph(NORMAL_TEXT, level, " ".join(parts))
if paragraph.runs or level is not None:
- paragraphs.append(paragraph)
+ paragraphs.append((first, paragraph))
pending = None
- for line in lines:
+ for number, line in enumerate(_lines(markdown)):
if fence is not None:
if line.strip().startswith(fence) and not line.strip().strip(fence[0]):
fence = None
continue
text = _clean(line.expandtabs(4))
runs = (Run(text, code=True),) if text else ()
- paragraphs.append(Paragraph(NORMAL_TEXT, None, runs))
+ paragraphs.append((number, Paragraph(NORMAL_TEXT, None, runs)))
continue
fence_match = _FENCE.match(line)
if fence_match is not None:
@@ -324,7 +415,7 @@ def parse(markdown: str) -> list[Paragraph]:
HEADING_STYLES[len(heading.group(1)) - 1], None, text
)
if paragraph.runs:
- paragraphs.append(paragraph)
+ paragraphs.append((number, paragraph))
continue
if _RULE.match(line):
flush()
@@ -339,43 +430,172 @@ def parse(markdown: str) -> list[Paragraph]:
if not list_indents or list_indents[-1] < indent:
list_indents.append(indent)
level = min(len(list_indents) - 1, MAX_NESTING_LEVEL)
- pending = (level, [bullet.group(2)])
+ pending = (number, level, [bullet.group(2)])
continue
if pending is not None:
# A continuation line of the paragraph or list item being gathered.
- pending[1].append(line.strip())
+ pending[2].append(line.strip())
continue
list_indents.clear()
- pending = (None, [line.strip()])
+ pending = (number, None, [line.strip()])
flush()
return paragraphs
-def split_blocks(paragraphs: list[Paragraph]) -> list[Block]:
- """The blocks of ``paragraphs``: the preamble, if any, then one per heading."""
- groups: list[tuple[tuple[str, ...], list[Paragraph]]] = []
+def _grouped(paragraphs: list[tuple[int, Paragraph]]) -> list[tuple[Block, int]]:
+ """The blocks of ``paragraphs``, each with the first line of its first paragraph."""
+ groups: list[tuple[tuple[str, ...], int, list[Paragraph]]] = []
path: list[tuple[int, str]] = [] # (level, text) of the enclosing headings
- for paragraph in paragraphs:
+ for line, paragraph in paragraphs:
if paragraph.style in HEADING_STYLES:
level = HEADING_STYLES.index(paragraph.style)
while path and path[-1][0] >= level:
path.pop()
path.append((level, paragraph.text))
- groups.append((tuple(text for _, text in path), [paragraph]))
+ groups.append((tuple(text for _, text in path), line, [paragraph]))
elif groups:
- groups[-1][1].append(paragraph)
+ groups[-1][2].append(paragraph)
else:
- groups.append(((), [paragraph]))
+ groups.append(((), line, [paragraph]))
seen: dict[tuple[str, ...], int] = {}
- blocks: list[Block] = []
- for block_path, block_paragraphs in groups:
+ blocks: list[tuple[Block, int]] = []
+ for block_path, line, block_paragraphs in groups:
occurrence = seen.get(block_path, 0)
seen[block_path] = occurrence + 1
key = json.dumps([list(block_path), occurrence], ensure_ascii=False)
block_id = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
- blocks.append(Block(block_id, block_path, tuple(block_paragraphs)))
+ blocks.append((Block(block_id, block_path, tuple(block_paragraphs)), line))
return blocks
+def split_blocks(paragraphs: list[Paragraph]) -> list[Block]:
+ """The blocks of ``paragraphs``: the preamble, if any, then one per heading."""
+ return [block for block, _ in _grouped([(0, p) for p in paragraphs])]
+
+
def parse_blocks(markdown: str) -> list[Block]:
- return split_blocks(parse(markdown))
+ return [block for block, _ in _grouped(_parse_lines(markdown))]
+
+
+class Span(NamedTuple):
+ """A block and where its text is in the Markdown it was parsed from."""
+
+ block: Block
+ start: int # character offsets: the start of the block's first line
+ end: int # the start of the next block's first line, or the end of the text
+
+
+_LINE_BREAK = re.compile("\r\n|\r|\n")
+
+
+def block_spans(markdown: str) -> list[Span]:
+ """The blocks of ``markdown``, each with the stretch of text it was parsed from.
+
+ A block's text runs from its first line up to the next block's, blank lines
+ and anything the target does not write (a horizontal rule) included; what
+ is before the first block belongs to none.
+ """
+ starts = [0] + [m.end() for m in _LINE_BREAK.finditer(markdown)]
+ blocks = _grouped(_parse_lines(markdown))
+ spans: list[Span] = []
+ for index, (block, line) in enumerate(blocks):
+ end = starts[blocks[index + 1][1]] if index + 1 < len(blocks) else len(markdown)
+ spans.append(Span(block, starts[line], end))
+ return spans
+
+
+# --- back to Markdown -------------------------------------------------------------
+
+# Escaped wherever they are: each can open a span (``*`` and ``_`` emphasis,
+# a code span, a link, an autolink) or is the escape itself.
+_ALWAYS_ESCAPED = set("\\`*[]<")
+_URL_SCHEME = re.compile(r"(https?):(?=//)")
+# What starts a line that is not a paragraph's: a heading, a list item, a fence.
+_LINE_START_ESCAPED = set("#-+~")
+
+
+def _escape(text: str) -> str:
+ out: list[str] = []
+ for i, char in enumerate(text):
+ if char in _ALWAYS_ESCAPED:
+ out.append("\\" + char)
+ elif char == "_" and not (
+ 0 < i < len(text) - 1 and text[i - 1].isalnum() and text[i + 1].isalnum()
+ ):
+ # ``snake_case`` cannot open emphasis; an ``_`` at a word's edge can.
+ out.append("\\_")
+ else:
+ out.append(char)
+ # A bare URL in plain text would be read back as a link.
+ return _URL_SCHEME.sub(r"\1\\:", "".join(out))
+
+
+def _code_span(text: str) -> str:
+ longest = max((len(m) for m in re.findall("`+", text)), default=0)
+ ticks = "`" * (longest + 1)
+ if (
+ text.startswith("`")
+ or text.endswith("`")
+ or (text.startswith(" ") and text.endswith(" ") and text.strip())
+ ):
+ text = f" {text} "
+ return ticks + text + ticks
+
+
+def _render_runs(runs: tuple[Run, ...]) -> str:
+ parts: list[str] = []
+ for index, run in enumerate(runs):
+ inner = _code_span(run.text) if run.code else _escape(run.text)
+ if run.bold and run.italic:
+ inner = f"**_{inner}_**"
+ elif run.bold:
+ inner = f"**{inner}**"
+ elif run.italic:
+ before = parts[-1][-1:] if parts else ""
+ after = runs[index + 1].text[:1] if index + 1 < len(runs) else ""
+ if runs[index + 1 :] and (runs[index + 1].bold or runs[index + 1].italic):
+ after = "*"
+ # ``_`` cannot open or close next to a letter; ``*`` closes wrongly
+ # right before ``**``.
+ marker = "_" if not before.isalnum() and not after.isalnum() else "*"
+ inner = f"{marker}{inner}{marker}"
+ if run.link is not None:
+ inner = f"[{inner}]({run.link})"
+ parts.append(inner)
+ return "".join(parts)
+
+
+def _render_paragraph(paragraph: Paragraph) -> str:
+ text = _render_runs(paragraph.runs)
+ if paragraph.style in HEADING_STYLES:
+ if text.endswith("#"):
+ text = text[:-1] + "\\#" # a closing sequence would be dropped
+ return "#" * (HEADING_STYLES.index(paragraph.style) + 1) + " " + text
+ if paragraph.bullet is not None:
+ return " " * paragraph.bullet + "- " + text
+ if text[:1] in _LINE_START_ESCAPED:
+ text = "\\" + text
+ return text
+
+
+def render(paragraphs: tuple[Paragraph, ...] | list[Paragraph]) -> str:
+ """Markdown that parses back to ``paragraphs``, each ``normalized``.
+
+ Empty paragraphs are left out, as ``fingerprint`` leaves them out. What the
+ subset cannot spell (a named style other than a heading, a list nested two
+ levels below its parent, a link whose URL has a space) reads back otherwise.
+ """
+ out: list[str] = []
+ previous: Paragraph | None = None
+ for paragraph in paragraphs:
+ paragraph = normalized(paragraph)
+ if not paragraph.runs:
+ continue
+ if previous is not None:
+ # A list item follows the one before it on the next line; anything
+ # else after a blank line, so it is not read as a continuation.
+ both_items = previous.bullet is not None and paragraph.bullet is not None
+ out.append("\n" if both_items else "\n\n")
+ out.append(_render_paragraph(paragraph))
+ previous = paragraph
+ return "".join(out)
diff --git a/python/cocoindex/connectors/google_docs/_reader.py b/python/cocoindex/connectors/google_docs/_reader.py
new file mode 100644
index 00000000..2d7bd6be
--- /dev/null
+++ b/python/cocoindex/connectors/google_docs/_reader.py
@@ -0,0 +1,181 @@
+"""Reading back a doc the target keeps: what a person changed in it.
+
+``read_doc`` takes the Markdown the doc was last declared with and returns it
+with each block a person edited in the doc replaced by the person's text (as
+Markdown, ``_markdown.render``) and each block a person deleted left out. A
+block is the person's when its text no longer matches the fingerprint its
+named range records (``_docs.classify``), the same test the target's writes
+use, so the reader and the writer never disagree about what a person did.
+
+A read is recorded as a data dependency of the caller (``coco.use_data_dep``),
+keyed by the sign-in's token file and the doc's tag. Its state is the doc, the
+revision read and a digest of what a person can change in the blocks
+(``_docs.observe``). Validating it asks Docs for the doc's revision; an
+unchanged one is valid at that, and so is the one the target's own write
+produced when the doc's stamp says that write was planned on the revision
+read (``_target.Stamp``). Otherwise the doc is read: it is still valid when
+its blocks are as they were read (a comment moved the revision), or as the
+target's write left them. Anything else re-runs the caller, which reads again.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from dataclasses import dataclass
+from typing import NamedTuple
+
+import cocoindex as coco
+from cocoindex._internal.context_keys import ContextKey
+from cocoindex.connectors.google_drive._oauth import SignInError
+
+from . import _docs, _markdown, _target
+from ._auth import UserAccount
+
+
+@dataclass(frozen=True)
+class DocRead:
+ """A doc ``declare_doc`` keeps, as read back with ``read_doc`` (experimental).
+
+ Attributes:
+ url: The doc's link.
+ content: The Markdown it was declared with, with each block a person
+ edited in the doc replaced by the person's text in Markdown, and
+ each block a person deleted left out. The rest is the declared
+ text exactly, so ``content == declared`` when no one changed a
+ block. Declaring ``content`` makes the doc the target's again.
+ edited: The heading paths of the blocks a person edited, in order, as
+ declared (``()`` for the text before the first heading).
+ deleted: The heading paths of the blocks a person deleted, in order.
+ """
+
+ url: str
+ content: str
+ edited: tuple[tuple[str, ...], ...]
+ deleted: tuple[tuple[str, ...], ...]
+
+
+# What a read saw, as its record keeps it: the doc, the revision read and
+# ``_docs.observe`` of it, or ``None`` when no doc had the tag.
+_Seen = tuple[str, str, str] | None
+
+
+class _Read(NamedTuple):
+ doc: DocRead | None
+ seen: _Seen
+
+
+def read_back(state: _docs.DocState, declared: str, url: str) -> DocRead:
+ """``declared`` with the blocks a person edited or deleted in ``state`` as they are there."""
+ out: list[str] = []
+ cursor = 0
+ edited: list[tuple[str, ...]] = []
+ deleted: list[tuple[str, ...]] = []
+ for span in _markdown.block_spans(declared):
+ block = span.block
+ rng = state.ranges.get(block.block_id)
+ if rng is not None:
+ status = _docs.classify(state, rng, _markdown.fingerprint(block.paragraphs))
+ if status != "kept":
+ continue
+ out.append(declared[cursor : span.start])
+ text = declared[span.start : span.end]
+ trailing = text[len(text.rstrip()) :]
+ if rng is None:
+ deleted.append(block.path)
+ else:
+ edited.append(block.path)
+ out.append(_markdown.render(state.content(rng)) + trailing)
+ cursor = span.end
+ out.append(declared[cursor:])
+ return DocRead(url, "".join(out), tuple(edited), tuple(deleted))
+
+
+def _read(account: UserAccount, tag: str, declared: str) -> _Read:
+ google = _target._Google(account)
+ found = google.find(tag)
+ if found is None:
+ return _Read(None, None)
+ state = _docs.read_document(google.get(found.doc_id))
+ doc = read_back(state, declared, _target.doc_url(found.doc_id))
+ return _Read(doc, (found.doc_id, state.revision_id, _docs.observe(state)))
+
+
+def _still_valid(key: tuple[str, str], prev: _Seen) -> coco.MemoStateOutcome:
+ token_path, tag = key
+ invalid = coco.MemoStateOutcome(state=prev, memo_valid=False)
+ try:
+ google = _target._Google(UserAccount(token_path))
+ found = google.find(tag)
+ if found is None:
+ return coco.MemoStateOutcome(state=None, memo_valid=prev is None)
+ if prev is not None and found.doc_id != prev[0]:
+ return invalid
+ revision = google.revision(found.doc_id)
+ if prev is not None and revision == prev[1]:
+ return coco.MemoStateOutcome(state=prev, memo_valid=True)
+ stamp = found.stamp
+ base = _target.NEW if prev is None else _target.short(prev[1])
+ # The target's own write, planned on the revision read, vouches for
+ # the doc as it left it (an empty ``observed`` vouches for nothing).
+ vouched = stamp.observed if stamp is not None and stamp.base == base else ""
+ if vouched and stamp is not None and _target.short(revision) == stamp.after:
+ return coco.MemoStateOutcome(
+ state=(found.doc_id, revision, vouched), memo_valid=True
+ )
+ state = _docs.read_document(google.get(found.doc_id))
+ observed = _docs.observe(state)
+ unchanged = prev is not None and observed == prev[2]
+ as_written = bool(vouched) and observed == vouched
+ if not (unchanged or as_written):
+ return invalid
+ return coco.MemoStateOutcome(
+ state=(found.doc_id, state.revision_id, observed), memo_valid=True
+ )
+ except SignInError:
+ # The caller re-runs and meets the missing sign-in in ``read_doc``,
+ # where it can be reported; a validator's error would fail the run.
+ return invalid
+
+
+async def _validate_read(key: tuple[str, str], prev: _Seen) -> coco.MemoStateOutcome:
+ return await asyncio.to_thread(_still_valid, key, prev)
+
+
+_DOC_READ = coco.DataDep("cocoindex.google_docs.read", validate=_validate_read)
+
+
+async def read_doc(
+ account: ContextKey[UserAccount], name: str, declared: str
+) -> DocRead | None:
+ """Read back the Google Doc ``declare_doc(account, name, ...)`` keeps (experimental).
+
+ ``declared`` is the Markdown the doc was last declared with, the content of
+ the run that last wrote it: the blocks a person deleted are those it has
+ and the doc no longer does, and the text of each block no one changed is
+ taken from it. ``None`` when there is no such doc (not created yet, or in
+ the trash).
+
+ The read is a data dependency of the caller: a person's edit or deletion
+ of a block, or the doc going to the trash or being replaced, makes a
+ memoized caller run again, and the target's own writes and a comment do
+ not. Each run validates it with one Drive and one Docs request, and reads
+ the doc when its revision moved for another reason than the target's write.
+
+ Args:
+ account: The ``ContextKey`` the run provides the signed-in
+ ``UserAccount`` under, as given to ``declare_doc``.
+ name: The doc's name, as given to ``declare_doc``.
+ declared: The Markdown the doc was last declared with.
+ """
+ user = coco.use_context(account)
+ tag = _target.tag_of(account.key, name)
+ read = await asyncio.to_thread(_read, user, tag, declared)
+ coco.use_data_dep(
+ _DOC_READ, key=(os.path.abspath(user.token_path), tag), state=read.seen
+ )
+ return read.doc
+
+
+__all__ = ["DocRead", "read_doc"]
diff --git a/python/cocoindex/connectors/google_docs/_target.py b/python/cocoindex/connectors/google_docs/_target.py
index 517e3ba6..9196bf75 100644
--- a/python/cocoindex/connectors/google_docs/_target.py
+++ b/python/cocoindex/connectors/google_docs/_target.py
@@ -1,21 +1,27 @@
"""Google Docs target: a doc the target creates and keeps in step with declared Markdown.
-The doc is found by a tag of the target's own (a Drive ``appProperties`` entry
-holding an id kept in the tracking record), not by its name, so a person may
-rename or move it. A change is written in place through the Docs API's
-``batchUpdate``: only the blocks whose content changed (see ``_docs.py``), with
-``requiredRevisionId`` so that an edit made while the target writes is read and
-planned around rather than overwritten. A block a person edited since the
-target wrote it keeps the person's text and is reported. Deleting the
-declaration moves the doc to the trash.
+The doc is found by a tag of the target's own (a Drive ``appProperties``
+entry derived from the declaration's context key and name), not by its title,
+so a person may rename or move it, and ``read_doc`` finds it too. A change is
+written in place through the Docs API's ``batchUpdate``: only the blocks whose
+content changed (see ``_docs.py``), with ``requiredRevisionId`` so that an
+edit made while the target writes is read and planned around rather than
+overwritten. A block a person edited since the target wrote it keeps the
+person's text and is reported. Deleting the declaration moves the doc to the
+trash.
+
+After each write the target stamps the doc (another ``appProperties`` entry)
+with the revision it planned on, the revision its write produced, and a digest
+of the blocks as it left them, so that ``read_doc``'s record can tell the
+target's own write from a person's edit without a second read.
"""
from __future__ import annotations
import asyncio
+import hashlib
import json
import logging
-import uuid
from dataclasses import dataclass
from typing import Any, Collection, NamedTuple, Sequence
@@ -55,6 +61,10 @@ _WRITE_ATTEMPTS = 3
_DOC_MIME = "application/vnd.google-apps.document"
# The Drive appProperties key that tags a doc with the target's id for it.
_TAG_PROPERTY = "cocoindexDoc"
+# The Drive appProperties key of the stamp a write leaves (see the module docstring).
+_STAMP_PROPERTY = "cocoindexWrite"
+# A stamp's base for a doc the target created in that write.
+NEW = "new"
# Raised when what a declaration writes changes, so every doc is planned again.
_FORMAT_VERSION = 1
@@ -79,10 +89,25 @@ class _DocKey(NamedTuple):
_KEY_CHECKER = TypeChecker(tuple[str, str])
+def tag_of(account_key: str, name: str) -> str:
+ """The target's id for the doc declared as ``name`` under ``account_key``.
+
+ It is in the doc's appProperties, so the doc is found by it: Google assigns
+ the doc's own id only when the sink creates it. It depends on the
+ declaration alone, as a table's name does for a database target, so a
+ reader finds the doc without the target's state, and a run with a new state
+ (another machine, a deleted state store) keeps writing to the same doc.
+ """
+ digest = hashlib.sha256(f"cocoindex/google_docs\0{account_key}\0{name}".encode())
+ return digest.hexdigest()[:32]
+
+
+def short(revision_id: str) -> str:
+ """A revision id as a stamp holds it: Drive limits a property to 124 bytes."""
+ return hashlib.sha256(revision_id.encode()).hexdigest()[:16]
+
+
class _DocRecord(msgspec.Struct, frozen=True):
- # The target's id for the doc, in the doc's appProperties: Google assigns
- # the doc's own id when the sink creates it, after this record is fixed.
- tag: str
content_fingerprint: bytes
# The blocks the declaration had: a later write tells a block a person
# deleted from one that is new.
@@ -92,7 +117,6 @@ class _DocRecord(msgspec.Struct, frozen=True):
@dataclass(frozen=True)
class _DocAction:
key: _DocKey
- tags: tuple[str, ...]
blocks: tuple[_markdown.Block, ...] | None # None: trash the doc
written_blocks: frozenset[str] | None
@@ -111,17 +135,15 @@ class _DocHandler(coco.TargetHandler[str, _DocRecord, None]):
/,
) -> coco.TargetReconcileOutput[_DocAction, _DocRecord, None] | None:
doc_key = _DocKey(*_KEY_CHECKER.check(key))
- tags = sorted({record.tag for record in prev_possible_records})
if coco.is_non_existence(desired_target_state):
- if not tags:
+ if not prev_possible_records:
return None
return coco.TargetReconcileOutput(
- action=_DocAction(doc_key, tuple(tags), None, None),
+ action=_DocAction(doc_key, None, None),
sink=_sink,
tracking_record=coco.NON_EXISTENCE,
)
content_fp = _content_fingerprint(desired_target_state)
- tag = tags[0] if tags else uuid.uuid4().hex
if (
not prev_may_be_missing
and prev_possible_records
@@ -133,10 +155,9 @@ class _DocHandler(coco.TargetHandler[str, _DocRecord, None]):
if len(prev_possible_records) == 1 and not prev_may_be_missing:
written = frozenset(next(iter(prev_possible_records)).block_ids)
return coco.TargetReconcileOutput(
- action=_DocAction(doc_key, (tag,), blocks, written),
+ action=_DocAction(doc_key, blocks, written),
sink=_sink,
tracking_record=_DocRecord(
- tag=tag,
content_fingerprint=content_fp,
block_ids=tuple(block.block_id for block in blocks),
),
@@ -184,30 +205,59 @@ def _execute(request: Any, retries: int = _RETRIES) -> Any:
raise explained from exc
+class Stamp(NamedTuple):
+ """What the target's last write to a doc left in its appProperties."""
+
+ base: str # the revision it planned on (``short``), or ``NEW`` for a doc it created
+ after: str # the revision its write produced (``short``)
+ observed: str # ``_docs.observe`` of the doc right after it; "" when unknown
+
+ def encode(self) -> str:
+ return f"{self.base}:{self.after}:{self.observed}"
+
+ @staticmethod
+ def decode(value: object) -> Stamp | None:
+ parts = str(value).split(":") if isinstance(value, str) else []
+ return Stamp(*parts) if len(parts) == 3 else None
+
+
+class Found(NamedTuple):
+ doc_id: str
+ stamp: Stamp | None
+
+
class _Google:
- """The Docs and Drive calls of one write, signed with the account's token."""
+ """The Docs and Drive calls of one write or read, signed with the account's token."""
def __init__(self, account: UserAccount) -> None:
http = AuthorizedHttp(account._credentials(), http=_new_http())
self._docs = build("docs", "v1", http=http, cache_discovery=False)
self._drive = build("drive", "v3", http=http, cache_discovery=False)
- def find(self, tag: str) -> str | None:
- """The doc tagged ``tag`` that is not in the trash; the oldest, if copies carry the tag."""
+ def find(self, tag: str) -> Found | None:
+ """The doc tagged ``tag`` that is not in the trash; the newest, when a
+ person restored an older one from the trash."""
query = (
f"appProperties has {{ key='{_TAG_PROPERTY}' and value='{tag}' }} "
"and trashed = false"
)
response = _execute(
self._drive.files().list(
- q=query, spaces="drive", fields="files(id, createdTime)", pageSize=100
+ q=query,
+ spaces="drive",
+ fields="files(id, createdTime, appProperties)",
+ pageSize=100,
)
)
files = sorted(
response.get("files", []),
key=lambda f: (str(f.get("createdTime", "")), str(f["id"])),
)
- return str(files[0]["id"]) if files else None
+ if not files:
+ return None
+ newest = files[-1]
+ properties = newest.get("appProperties") or {}
+ return Found(str(newest["id"]), Stamp.decode(properties.get(_STAMP_PROPERTY)))
def create(self, name: str, tag: str) -> str:
body = {
@@ -231,6 +281,15 @@ class _Google:
if exc.resp.status != 404:
raise
+ def stamp(self, doc_id: str, stamp: Stamp) -> None:
+ _execute(
+ self._drive.files().update(
+ fileId=doc_id,
+ body={"appProperties": {_STAMP_PROPERTY: stamp.encode()}},
+ fields="id",
+ )
+ )
+
def get(self, doc_id: str) -> Any:
return _execute(
self._docs.documents().get(
@@ -238,61 +297,79 @@ class _Google:
)
)
+ def revision(self, doc_id: str) -> str:
+ current = _execute(
+ self._docs.documents().get(documentId=doc_id, fields="revisionId")
+ )
+ return str(current.get("revisionId", ""))
+
def update(
self, doc_id: str, requests: list[dict[str, Any]], revision_id: str
- ) -> bool:
- """Apply ``requests`` to revision ``revision_id``; ``False`` when the doc moved on."""
+ ) -> _Written | None:
+ """Apply ``requests`` to revision ``revision_id``; ``None`` when the doc moved on."""
body = {
"requests": requests,
"writeControl": {"requiredRevisionId": revision_id},
}
try:
- _execute(self._docs.documents().batchUpdate(documentId=doc_id, body=body))
+ response = _execute(
+ self._docs.documents().batchUpdate(documentId=doc_id, body=body)
+ )
except HttpError as exc:
if exc.resp.status != 400:
raise
- current = _execute(
- self._docs.documents().get(documentId=doc_id, fields="revisionId")
- )
- if current.get("revisionId") == revision_id:
+ if self.revision(doc_id) == revision_id:
raise
- return False
- return True
+ return None
+ after = (response.get("writeControl") or {}).get("requiredRevisionId")
+ return _Written(str(after) if after else None)
+
+
+class _Written(NamedTuple):
+ # The revision the write produced, as Docs reports it; None when it did not.
+ after: str | None
def _apply_action(account: UserAccount, action: _DocAction) -> None:
google = _Google(account)
name = action.key.name
+ tag = tag_of(*action.key)
+ found = google.find(tag)
if action.blocks is None:
- for tag in action.tags:
- doc_id = google.find(tag)
- if doc_id is not None:
- google.trash(doc_id)
- _logger.info(
- "Moved Google Doc %r to the trash: %s", name, doc_url(doc_id)
- )
+ if found is not None:
+ google.trash(found.doc_id)
+ _logger.info(
+ "Moved Google Doc %r to the trash: %s", name, doc_url(found.doc_id)
+ )
return
- (tag,) = action.tags
written_blocks = action.written_blocks
- doc_id = google.find(tag)
- if doc_id is None:
+ created = found is None
+ if found is None:
doc_id = google.create(name, tag)
# A new doc (the first, or one replacing a doc that was deleted or
# trashed) has none of the blocks yet; none of them was deleted by a person.
written_blocks = None
_logger.info("Created Google Doc %r: %s", name, doc_url(doc_id))
+ else:
+ doc_id = found.doc_id
+ written: _Written | None = None
for _ in range(_WRITE_ATTEMPTS):
state = _docs.read_document(google.get(doc_id))
plan = _docs.plan_write(state, action.blocks, written_blocks)
- if not plan.requests or google.update(doc_id, plan.requests, state.revision_id):
+ if not plan.requests:
+ break
+ written = google.update(doc_id, plan.requests, state.revision_id)
+ if written is not None:
break
else:
raise RuntimeError(
f"Google Doc {name!r} ({doc_url(doc_id)}) changed every time CocoIndex "
f"read it to write, {_WRITE_ATTEMPTS} times; run again once it is quiet."
)
+ if written is not None or created:
+ _stamp(google, doc_id, NEW if created else short(state.revision_id), written)
if plan.person_edits:
_logger.warning(
"Google Doc %r (%s) keeps a person's edits; CocoIndex left these blocks "
@@ -303,6 +380,19 @@ def _apply_action(account: UserAccount, action: _DocAction) -> None:
)
+def _stamp(google: _Google, doc_id: str, base: str, written: _Written | None) -> None:
+ """Record that the doc's latest revision is the target's own write, planned
+ on ``base``: read it again, and stamp it only if no one edited it since."""
+ state = _docs.read_document(google.get(doc_id))
+ after = written.after if written is not None else None
+ if after is None or after == state.revision_id:
+ observed = _docs.observe(state)
+ after = state.revision_id
+ else:
+ observed = "" # someone edited after the write; no stamp vouches for it
+ google.stamp(doc_id, Stamp(base, short(after), observed))
+
+
def _describe(edit: _docs.PersonEdit) -> str:
if edit.kind == "deleted":
what = "deleted; the flow still declares it, and it was not written back"
diff --git a/python/tests/connectors/test_google_docs_target.py b/python/tests/connectors/test_google_docs_target.py
index 1c383f38..98a7ebb1 100644
--- a/python/tests/connectors/test_google_docs_target.py
+++ b/python/tests/connectors/test_google_docs_target.py
@@ -470,7 +470,11 @@ class FakeGoogle:
return 400, {"error": {"code": 400, "message": str(exc)}}
doc.commit(trial, origin)
doc.revision += 1
- return 200, {"documentId": doc_id, "replies": [{} for _ in payload["requests"]]}
+ return 200, {
+ "documentId": doc_id,
+ "replies": [{} for _ in payload["requests"]],
+ "writeControl": {"requiredRevisionId": f"rev-{doc.revision}"},
+ }
def _drive_api(
self, method: str, path: str, query: dict[str, str], payload: Any
@@ -495,13 +499,23 @@ class FakeGoogle:
)
assert "trashed = false" in q
found = [
- {"id": f["id"], "createdTime": f["createdTime"]}
+ {
+ "id": f["id"],
+ "createdTime": f["createdTime"],
+ "appProperties": dict(f["appProperties"]),
+ }
for f in self.files.values()
if f["appProperties"].get(key) == value and not f["trashed"]
]
return 200, {"files": found}
file_id = path.removeprefix("/drive/v3/files/")
if method == "PATCH" and file_id in self.files:
+ # Drive merges appProperties key by key; the doc's revision is
+ # untouched, as metadata is not content.
+ payload = dict(payload)
+ self.files[file_id]["appProperties"].update(
+ payload.pop("appProperties", None) or {}
+ )
self.files[file_id].update(payload)
return 200, {"id": file_id}
return 404, {"error": {"code": 404, "message": "File not found"}}
@@ -663,7 +677,8 @@ def test_the_first_run_creates_the_doc_with_a_named_range_per_block(
(file,) = google.files.values()
assert file["name"] == "Weekly brief"
assert file["mimeType"] == "application/vnd.google-apps.document"
- assert set(file["appProperties"]) == {"cocoindexDoc"}
+ # The tag the doc is found by, and the stamp of the target's last write.
+ assert set(file["appProperties"]) == {"cocoindexDoc", "cocoindexWrite"}
doc = google.only_doc()
assert doc.lines() == [
("NORMAL_TEXT", None, "Kept current from the sources."),
@@ -702,8 +717,8 @@ def test_the_first_run_creates_the_doc_with_a_named_range_per_block(
_docs.plan_write(state, blocks, frozenset(b.block_id for b in blocks)).requests
== []
)
- # One create, one batchUpdate.
- assert [m for m, _ in google.writes()] == ["POST", "POST"]
+ # One create, one batchUpdate, one stamp.
+ assert [m for m, _ in google.writes()] == ["POST", "POST", "PATCH"]
def test_an_unchanged_rerun_makes_no_api_call(setup: Setup) -> None:
@@ -739,7 +754,8 @@ def test_a_changed_section_rewrites_only_its_changed_paragraphs(setup: Setup) ->
)
setup.run(app, changed)
- assert [m for m, _ in setup.google.writes()] == ["POST"] # one batchUpdate
+ # One batchUpdate, and the stamp.
+ assert [m for m, _ in setup.google.writes()] == ["POST", "PATCH"]
assert (
"NORMAL_TEXT",
0,
@@ -1300,3 +1316,237 @@ def test_random_successive_versions_leave_exactly_the_declared_doc(
state = _docs.read_document(doc.to_json())
assert _docs.plan_write(state, blocks, None).requests == [], f"step {step}"
assert set(state.ranges) == {b.block_id for b in blocks}
+
+
+# --- reading back a person's edits --------------------------------------------------
+
+
+def _read(setup: Setup, declared: str) -> google_docs.DocRead | None:
+ """``read_doc`` run in a component of its own app, as a flow would."""
+ out: dict[str, google_docs.DocRead | None] = {}
+
+ @coco.fn
+ async def main() -> None:
+ out["read"] = await google_docs.read_doc(GDOCS, "Weekly brief", declared)
+
+ setup.google.calls.clear()
+ coco.App(
+ coco.AppConfig(name="read_back", environment=coco_env), main
+ ).update_blocking()
+ return out["read"]
+
+
+def _person_deletes_block(doc: FakeDoc, block: _markdown.Block) -> None:
+ (rid,) = [
+ r for r, n in doc.range_names().items() if n.split(":")[1] == block.block_id
+ ]
+ _, start, end = doc.ranges[rid]
+ doc.delete(start, end)
+ doc.revision += 1
+
+
+def test_read_doc_hands_back_a_persons_edits_in_the_declared_markdown(
+ setup: Setup,
+) -> None:
+ setup.run(setup.app("read_back_doc"), BRIEF)
+ doc = setup.google.only_doc()
+ (doc_id,) = setup.google.files
+
+ # Nothing changed by a person: the declared text exactly, and two reads.
+ read = _read(setup, BRIEF)
+ assert read == google_docs.DocRead(
+ url=f"https://docs.google.com/document/d/{doc_id}/edit",
+ content=BRIEF,
+ edited=(),
+ deleted=(),
+ )
+ assert [m for m, _ in setup.google.calls] == ["GET", "GET"] # find, read
+ assert setup.google.writes() == []
+
+ # A person rewords a sentence in Risks (bold included), deletes Sources,
+ # comments on Decisions, and adds an empty paragraph to the preamble.
+ doc.person_replace("Google may change", "Google could change")
+ doc.comment("Ship the")
+ doc.insert(doc.find("Kept current") + len("Kept current from the sources."), "\n")
+ doc.revision += 1
+ _person_deletes_block(doc, _blocks(BRIEF)[4])
+
+ read = _read(setup, BRIEF)
+ assert read is not None
+ assert read.edited == (("Brief", "Risks"),)
+ assert read.deleted == (("Brief", "Sources"),)
+ assert read.content == BRIEF.replace(
+ "## Risks\n\nGoogle may change *named range* behavior.\n\n",
+ "## Risks\n\nGoogle could change _named range_ behavior.\n\n",
+ ).replace("## Sources\n\nhttps://example.com/a and https://example.com/b.\n", "")
+ # The person's text parses back to what the doc holds.
+ risks = _markdown.parse_blocks(read.content)[3]
+ state = _docs.read_document(doc.to_json())
+ assert _markdown.fingerprint(risks.paragraphs) == _markdown.fingerprint(
+ state.content(state.ranges[risks.block_id])
+ )
+ assert setup.google.writes() == [] # reading writes nothing
+
+
+def test_declaring_the_content_read_back_makes_the_blocks_the_targets_again(
+ setup: Setup, caplog: pytest.LogCaptureFixture
+) -> None:
+ app = setup.app("adopt")
+ setup.run(app, BRIEF)
+ doc = setup.google.only_doc()
+ doc.person_replace("Google may change", "Google could change")
+ on_edit = doc.comment("could change")
+ read = _read(setup, BRIEF)
+ assert read is not None and read.edited == (("Brief", "Risks"),)
+
+ with caplog.at_level(logging.WARNING, logger=_target.__name__):
+ setup.run(app, read.content)
+ assert not _warnings(caplog) # nothing kept from the flow any more
+ assert doc.comment_survives(on_edit) # the person's text is not rewritten
+ assert _read(setup, read.content) == google_docs.DocRead(
+ read.url, read.content, (), ()
+ )
+ # The block is the flow's again: its next change is written.
+ setup.run(app, read.content.replace("could change", "will change"))
+ assert (
+ "NORMAL_TEXT",
+ None,
+ "Google will change named range behavior.",
+ ) in doc.lines()
+
+
+def test_a_heading_a_person_renamed_is_taken_in_without_a_second_copy(
+ setup: Setup,
+) -> None:
+ app = setup.app("rename")
+ markdown = "## Plan\n\n### Risks\n\nr1\n\n### Costs\n\nc1\n\n## Next\n\nn1\n"
+ setup.run(app, markdown)
+ doc = setup.google.only_doc()
+ on_c1 = doc.comment("c1")
+ doc.person_replace("Plan", "The plan") # renames the blocks under it too
+ read = _read(setup, markdown)
+ assert read is not None and read.edited == (("Plan",),)
+ assert read.content == markdown.replace("## Plan", "## The plan")
+
+ setup.run(app, read.content)
+ assert [text for _, _, text in doc.lines()] == [
+ "The plan",
+ "Risks",
+ "r1",
+ "Costs",
+ "c1",
+ "Next",
+ "n1",
+ ]
+ assert doc.comment_survives(on_c1) # the blocks under it were not rewritten
+ state = _docs.read_document(doc.to_json())
+ assert set(state.ranges) == {b.block_id for b in _blocks(read.content)}
+ assert _docs.plan_write(state, _blocks(read.content), None).requests == []
+
+
+_watch_runs: list[str | None] = []
+
+
+async def _watch(declared: str) -> None:
+ read = await google_docs.read_doc(GDOCS, "Weekly brief", declared)
+ _watch_runs.append(None if read is None else read.content)
+
+
+def test_a_read_reruns_its_reader_on_a_persons_edit_only(setup: Setup) -> None:
+ """The read's record survives the target's own writes (a create, an update,
+ a person's edit taken in) and a comment, and not a person's edit."""
+ content: dict[str, str] = {"content": BRIEF}
+
+ @coco.fn
+ async def main() -> None:
+ google_docs.declare_doc(GDOCS, "Weekly brief", content["content"])
+ await coco.use_mount(coco.component_subpath("watch"), _watch, BRIEF)
+
+ app = coco.App(coco.AppConfig(name="watch", environment=coco_env), main)
+ _watch_runs.clear()
+
+ def run(new: str | None = None) -> int:
+ if new is not None:
+ content["content"] = new
+ before = len(_watch_runs)
+ app.update_blocking()
+ return len(_watch_runs) - before
+
+ assert run() == 1 and _watch_runs[-1] is None # read before the doc existed
+ assert run() == 0 # the target created it: not a change by a person
+ assert run(BRIEF.replace("Ship the", "Ship the new")) == 0
+ assert run() == 0 # after the target's own update
+ doc = setup.google.only_doc()
+ doc.comment("Google may")
+ doc.revision += 1 # a comment may move the revision
+ assert run() == 0
+ doc.person_replace("Google may change", "Google could change")
+ assert run() == 1 and "Google could change" in str(_watch_runs[-1])
+ assert run() == 0
+ # The flow takes the person's text in: the target's write, planned on the
+ # revision the reader read, makes the blocks the target's again.
+ edited = BRIEF.replace("Ship the", "Ship the new").replace(
+ "Google may change *named range*", "Google could change _named range_"
+ )
+ assert run(edited) == 0
+ assert run() == 0
+ _person_deletes_block(doc, _blocks(BRIEF)[1]) # the preamble
+ assert run() == 1
+ assert run() == 0
+ # A person trashes the doc: the reader runs and finds none.
+ (doc_id,) = setup.google.files
+ setup.google.files[doc_id]["trashed"] = True
+ content["content"] = BRIEF # ... and the target writes a new one next run
+ before = len(_watch_runs)
+ app.update_blocking()
+ assert len(_watch_runs) - before == 1 and _watch_runs[-1] is None
+
+
+def test_the_doc_is_the_same_for_a_run_with_a_new_state(setup: Setup) -> None:
+ """The doc's tag comes from the declaration, so a fresh state store (another
+ machine, a deleted database) finds the doc rather than creating a copy."""
+ setup.run(setup.app("first_state"), BRIEF)
+ (doc_id,) = setup.google.files
+ setup.run(setup.app("second_state"), BRIEF.replace("Ship the", "Ship the new"))
+ assert list(setup.google.files) == [doc_id]
+ assert "Ship the new connector in 1.3." in [
+ t for _, _, t in setup.google.only_doc().lines()
+ ]
+
+
+_ROUND_TRIP = [
+ "plain words, with punctuation: a; b! (c) [d] e_f *g* `h` <i> 1. 2) #3 \\\\ ~",
+ "**bold**, *italic*, ***both***, `code`, `` a ` b ``, and **bold `code`**",
+ "a [link](https://e.com/a_(b)), <https://e.com/c>, https://e.com/d. done",
+ "snake_case and _italic_ and __bold__ and a*b*c",
+ "- item with **bold**\n - nested *italic*\n - deeper `code`\n- back",
+ "## Heading with *style* and a #tag #",
+ "# Top\n\n### Skips a level",
+ "\\# not a heading, \\- not an item, \\+ not either, \\~~~ no fence",
+ "text ending in a backslash \\\\",
+ "Café 🎉 — “quotes” and an em dash",
+]
+
+
[email protected]("markdown", _ROUND_TRIP)
+def test_rendered_markdown_parses_back_to_the_same_paragraphs(markdown: str) -> None:
+ paragraphs = _markdown.parse(markdown)
+ rendered = _markdown.render(paragraphs)
+ assert _markdown.parse(rendered) == [_markdown.normalized(p) for p in paragraphs]
+ assert _markdown.render(_markdown.parse(rendered)) == rendered
+
+
+def test_whitespace_a_person_adds_is_not_an_edit() -> None:
+ run = _markdown.Run
+ written = _markdown.parse("a **bold** word")
+ typed = [
+ _markdown.Paragraph(
+ "NORMAL_TEXT",
+ None,
+ (run(" a "), run("bold ", bold=True), run("word ")),
+ ),
+ _markdown.Paragraph("NORMAL_TEXT", None, ()),
+ ]
+ assert _markdown.fingerprint(typed) == _markdown.fingerprint(written)
+ assert _markdown.render(typed) == "a **bold** word"