path_utils.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. """Path-component helpers shared by execution environment backends. Kept separate from the
  2. base class so lazy backend imports do not depend on newly added exports from a large module
  3. cached earlier in a long-lived process."""
  4. from __future__ import annotations
  5. import hashlib
  6. import re
  7. # A persistent sandbox's host directory is named after task_id, and that name
  8. # then becomes the source half of a Docker bind spec or a plugin backend's
  9. # writable overlay directory (singularity). Keep every backend on one collision-safe mapping.
  10. _SANDBOX_DIR_UNSAFE_RE = re.compile(r"[^A-Za-z0-9._-]")
  11. _SANDBOX_DIR_MAX_LEN = 128
  12. _SANDBOX_DIR_HASH_LEN = 12
  13. def sanitize_task_id_for_path(task_id: str) -> str:
  14. """Bind-mountable directory name for *task_id*'s sandbox. Already-safe names are returned
  15. verbatim (preserving existing sandbox locations); rewritten names carry a digest because
  16. substitution alone is not injective: ``a:b`` and ``a_b`` must not share state."""
  17. value = task_id if isinstance(task_id, str) else ""
  18. if not value:
  19. return "default"
  20. cleaned = _SANDBOX_DIR_UNSAFE_RE.sub("_", value)
  21. if (cleaned == value and len(value) <= _SANDBOX_DIR_MAX_LEN
  22. and value not in {".", ".."} and not value.endswith((".", " "))):
  23. return value
  24. digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:_SANDBOX_DIR_HASH_LEN]
  25. stem = cleaned[: _SANDBOX_DIR_MAX_LEN - _SANDBOX_DIR_HASH_LEN - 1].strip("._")
  26. return f"{stem or 'task'}-{digest}"