process_registry_env_log.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. """Incremental sandbox log reads for ProcessRegistry's non-local poller."""
  2. def log_delta_command(quoted_log_path: str, offset: int) -> str:
  3. """Shell command that reads only the log bytes written since ``offset``
  4. (``cat``-ing the whole file every poll re-sends all output over docker/SSH).
  5. Prints one header line ``"<size> <offset>"`` then the bytes in [offset, size).
  6. The size is read first and the tail cut at that same size, so a growing file
  7. never sends a byte twice; a file that shrank was rotated/truncated, so the
  8. offset drops to 0 and the reader starts over. The window end is pulled back
  9. to a UTF-8 character boundary (the backend decodes each ``execute()`` result
  10. on its own, so a straddling multibyte char would become U+FFFD and break watch
  11. patterns at the seam): up to 3 trailing continuation bytes are held for the
  12. next poll and the header reports the trimmed size."""
  13. return (
  14. f"O={offset}; "
  15. f"S=$({{ wc -c < {quoted_log_path}; }} 2>/dev/null | tr -dc '0-9'); "
  16. f"S=${{S:-0}}; "
  17. f'if [ "$S" -lt "$O" ]; then O=0; fi; '
  18. # Scan back up to 3 continuation bytes (octal 200-277) to the lead byte; if
  19. # the lead's declared length (3xx=2, 34x-35x=3, 36x-37x=4) exceeds the bytes
  20. # present, trim to before it. Complete sequences and ASCII tails untouched.
  21. f'N=0; P=$S; while [ "$P" -gt "$O" ] && [ "$N" -lt 3 ]; do '
  22. f"B=$(tail -c +$P {quoted_log_path} 2>/dev/null | head -c 1 | od -An -to1 | tr -dc '0-9'); "
  23. f'case "$B" in 2[0-7][0-7]) P=$((P-1)); N=$((N+1));; *) break;; esac; done; '
  24. f'if [ "$N" -gt 0 ] || [ "$P" -eq "$S" ]; then '
  25. f"B=$(tail -c +$P {quoted_log_path} 2>/dev/null | head -c 1 | od -An -to1 | tr -dc '0-9'); "
  26. f'case "$B" in 3[0-3][0-7]) L=2;; 3[4-5][0-7]) L=3;; 3[6-7][0-7]) L=4;; *) L=1;; esac; '
  27. f'if [ "$L" -gt $((N+1)) ]; then S=$((P-1)); fi; fi; '
  28. f'echo "$S $O"; '
  29. f'if [ "$S" -gt "$O" ]; then '
  30. f"tail -c +$((O+1)) {quoted_log_path} 2>/dev/null | head -c $((S-O)); fi"
  31. )