|
| 1 | +"""Builds state keys, so that plugins choose how finely they track progress without inventing key formats.""" |
| 2 | + |
| 3 | +from typing import Optional, Union |
| 4 | + |
| 5 | +_SEPARATOR = "|" |
| 6 | +_ASSIGN = "=" |
| 7 | +_ESCAPE = "\\" |
| 8 | + |
| 9 | + |
| 10 | +def _escape(part: str) -> str: |
| 11 | + return ( |
| 12 | + part.replace(_ESCAPE, _ESCAPE * 2) |
| 13 | + .replace(_SEPARATOR, _ESCAPE + _SEPARATOR) |
| 14 | + .replace(_ASSIGN, _ESCAPE + _ASSIGN) |
| 15 | + ) |
| 16 | + |
| 17 | + |
| 18 | +def state_key( |
| 19 | + table: str, |
| 20 | + *, |
| 21 | + client_id: Optional[str] = None, |
| 22 | + **partition: Union[str, int], |
| 23 | +) -> str: |
| 24 | + """ |
| 25 | + Returns the state key of a table's progress, optionally for one client and one partition of the table. |
| 26 | +
|
| 27 | + A table with one cursor uses ``state_key("items")``. A table that tracks progress per parent, account or |
| 28 | + other partition passes the fields that identify it, e.g. ``state_key("responses", form_id=form["id"])``. |
| 29 | + Each such key is its own state row: with checkpoints, a partition's state waits only for the resources of |
| 30 | + the table resolver that set it, and the CLI persists the keys changed since its last commit together. |
| 31 | +
|
| 32 | + Keys are readable and deterministic: partition fields are sorted, and separators in names and values are |
| 33 | + escaped, so different tables, clients or partitions never share a key. |
| 34 | +
|
| 35 | + Example: |
| 36 | + >>> state_key("responses", client_id="acct-1", form_id=123) |
| 37 | + 'responses|client_id=acct-1|form_id=123' |
| 38 | + """ |
| 39 | + parts = [_escape(table)] |
| 40 | + if client_id is not None: |
| 41 | + parts.append(f"client_id{_ASSIGN}{_escape(client_id)}") |
| 42 | + for name in sorted(partition): |
| 43 | + parts.append(f"{_escape(name)}{_ASSIGN}{_escape(str(partition[name]))}") |
| 44 | + return _SEPARATOR.join(parts) |
0 commit comments