paths.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """Dotted-path grammar of the config plane wire contract (contract.md §3).
  2. A path is a list of mapping keys. On the wire it is one string: each segment escapes ``\\`` as
  3. ``\\\\`` and ``.`` as ``\\.``, and segments are joined with ``.``. Coverage (lock matching) is
  4. segment-wise, never a string prefix (§3.4).
  5. """
  6. from __future__ import annotations
  7. from typing import Iterable, List, Optional, Sequence, Tuple
  8. Path = tuple[str, ...]
  9. class PathError(ValueError):
  10. """An encoded path that does not parse (§3.3)."""
  11. def encode(segments: Sequence[str]) -> str:
  12. return ".".join(s.replace("\\", "\\\\").replace(".", "\\.") for s in segments)
  13. def decode(encoded: str) -> Path:
  14. segments: list[str] = []
  15. current: list[str] = []
  16. i = 0
  17. while i < len(encoded):
  18. ch = encoded[i]
  19. if ch == "\\":
  20. if i + 1 >= len(encoded) or encoded[i + 1] not in "\\.":
  21. raise PathError(f"invalid escape in config path {encoded!r}")
  22. current.append(encoded[i + 1])
  23. i += 2
  24. continue
  25. if ch == ".":
  26. if not current:
  27. raise PathError(f"empty segment in config path {encoded!r}")
  28. segments.append("".join(current))
  29. current = []
  30. else:
  31. current.append(ch)
  32. i += 1
  33. if not current:
  34. raise PathError(f"empty segment in config path {encoded!r}")
  35. segments.append("".join(current))
  36. validate(segments, encoded)
  37. return tuple(segments)
  38. MAX_SEGMENTS = 32
  39. MAX_SEGMENT_BYTES = 256
  40. MAX_ENCODED_BYTES = 2048
  41. def validate(segments: Sequence[str], encoded: Optional[str] = None) -> None:
  42. """§3.1 segment and path limits (the plane rejects violations with ``config_path_invalid``)."""
  43. shown = encoded if encoded is not None else encode(segments)
  44. if not 1 <= len(segments) <= MAX_SEGMENTS:
  45. raise PathError(f"config path {shown!r} must have 1-{MAX_SEGMENTS} segments")
  46. if len((encoded if encoded is not None else encode(segments)).encode("utf-8")) > MAX_ENCODED_BYTES:
  47. raise PathError(f"config path is longer than {MAX_ENCODED_BYTES} bytes")
  48. for seg in segments:
  49. if not 1 <= len(seg.encode("utf-8")) <= MAX_SEGMENT_BYTES:
  50. raise PathError(f"config path {shown!r}: a segment must be 1-{MAX_SEGMENT_BYTES} bytes")
  51. if any(ord(c) < 0x20 or ord(c) == 0x7F for c in seg):
  52. raise PathError(f"config path {shown!r}: control character in a segment")
  53. if seg == "__proto__":
  54. raise PathError(f"reserved segment '__proto__' in config path {shown!r}")
  55. def covers(lock: Sequence[str], path: Sequence[str]) -> bool:
  56. """``lock`` covers ``path`` when it is a segment-wise prefix of it (equal counts)."""
  57. return len(lock) <= len(path) and tuple(path[:len(lock)]) == tuple(lock)
  58. def covering_lock(locks: Iterable[tuple[Path, str]], path: Sequence[str]) -> Optional[tuple[Path, str]]:
  59. """The first ``(lock, level)`` whose lock covers ``path``, or None."""
  60. for lock, level in locks:
  61. if covers(lock, path):
  62. return lock, level
  63. return None
  64. def from_dotted(dotted: str) -> Path:
  65. """A dotted key as the CLI and in-tree callers spell it. Those callers never escape, so a key
  66. that does not parse as an encoded path is split on every ``.`` (today's behaviour)."""
  67. try:
  68. return decode(dotted)
  69. except PathError:
  70. return tuple(dotted.split("."))