Skip to content

CLI for SidePulse

Python

Share uncached status reader for read-only keepalive

Peter Kuhar2f8e6af221ca
diff --git a/src/sidepulse/_vendor/read2me.py b/src/sidepulse/_vendor/read2me.py
index 6472999..61af15e 100644
--- a/src/sidepulse/_vendor/read2me.py
+++ b/src/sidepulse/_vendor/read2me.py
@@ -65,84 +65,7 @@ def decode_status(data: bytes) -> dict:
return result
-class _MacFile:
- """Read-only, aligned positional I/O; also used for fresh ordinary file reads."""
- def __init__(self, path: Path, expected_size=None):
- if sys.platform != "darwin":
- raise OSError("READ2ME hardware transport currently supports macOS only")
- import fcntl
- self.libc = ctypes.CDLL(None, use_errno=True)
- self.libc.posix_memalign.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t, ctypes.c_size_t]
- self.libc.pread.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_longlong]
- self.libc.pread.restype = ctypes.c_ssize_t
- self.libc.free.argtypes = [ctypes.c_void_p]
- self.buffer = ctypes.c_void_p()
- self.fd = os.open(path, os.O_RDONLY)
- try:
- if expected_size is not None and os.fstat(self.fd).st_size != expected_size:
- raise ValueError(f"control file must be exactly {expected_size} bytes")
- fcntl.fcntl(self.fd, 48, 1) # Darwin F_NOCACHE
- fcntl.fcntl(self.fd, 45, 0) # Darwin F_RDAHEAD
- # F_NOCACHE alone is insufficient: an unaligned Python bytes buffer
- # makes macOS read surrounding sectors, corrupting address symbols.
- page_size = os.sysconf("SC_PAGESIZE")
- result = self.libc.posix_memalign(ctypes.byref(self.buffer), page_size, page_size)
- if result:
- raise OSError(result, os.strerror(result))
- except BaseException:
- os.close(self.fd)
- raise
-
- def __enter__(self):
- return self
-
- def __exit__(self, *exc):
- self.close()
-
- def close(self):
- if self.fd < 0:
- return
- self.libc.free(self.buffer)
- self.buffer = ctypes.c_void_p()
- os.close(self.fd)
- self.fd = -1
-
- def invalidate_cache(self):
- """Evict existing cached pages before reading an ordinary status file."""
- if self.fd < 0:
- raise ValueError("channel is closed")
- size = os.fstat(self.fd).st_size
- if size == 0:
- return
- self.libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,
- ctypes.c_int, ctypes.c_int, ctypes.c_longlong]
- self.libc.mmap.restype = ctypes.c_void_p
- self.libc.msync.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
- self.libc.msync.restype = ctypes.c_int
- self.libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]
- self.libc.munmap.restype = ctypes.c_int
- # PROT_READ | MAP_SHARED; never access the mapping itself.
- address = self.libc.mmap(None, size, 1, 1, self.fd, 0)
- if address == ctypes.c_void_p(-1).value:
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error))
- try:
- if self.libc.msync(address, size, 2) != 0: # MS_INVALIDATE
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error))
- finally:
- if self.libc.munmap(address, size) != 0:
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error))
-
- def read_at(self, offset: int) -> bytes:
- if self.fd < 0:
- raise ValueError("channel is closed")
- count = self.libc.pread(self.fd, self.buffer, 512, offset)
- if count < 0:
- error = ctypes.get_errno()
- raise OSError(error, os.strerror(error))
- return ctypes.string_at(self.buffer, count)
+from ..status_reader import _MacFile
class Channel(_MacFile):
diff --git a/src/sidepulse/keep_awake.py b/src/sidepulse/keep_awake.py
index 3715eaa..b5f33af 100644
--- a/src/sidepulse/keep_awake.py
+++ b/src/sidepulse/keep_awake.py
@@ -200,7 +200,7 @@ def keepalive_file_for_target(target: Path) -> Path:
def read_status_file(path: Path) -> None:
from .device_writer import device_write_lock
- from .readonly_control import read_status_bytes
+ from .status_reader import read_status_bytes
with device_write_lock(path.parent):
read_status_bytes(path)
diff --git a/src/sidepulse/status_reader.py b/src/sidepulse/status_reader.py
new file mode 100644
index 0000000..99fef6d
--- /dev/null
+++ b/src/sidepulse/status_reader.py
@@ -0,0 +1,105 @@
+"""Fresh, read-only device status reads, including cached macOS volumes."""
+from __future__ import annotations
+
+import ctypes
+import os
+import sys
+from pathlib import Path
+
+
+class _MacFile:
+ """Read-only, aligned positional I/O; also used for fresh ordinary file reads."""
+ def __init__(self, path: Path, expected_size=None):
+ if sys.platform != "darwin":
+ raise OSError("READ2ME hardware transport currently supports macOS only")
+ import fcntl
+ self.libc = ctypes.CDLL(None, use_errno=True)
+ self.libc.posix_memalign.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t, ctypes.c_size_t]
+ self.libc.pread.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_longlong]
+ self.libc.pread.restype = ctypes.c_ssize_t
+ self.libc.free.argtypes = [ctypes.c_void_p]
+ self.buffer = ctypes.c_void_p()
+ self.fd = os.open(path, os.O_RDONLY)
+ try:
+ if expected_size is not None and os.fstat(self.fd).st_size != expected_size:
+ raise ValueError(f"control file must be exactly {expected_size} bytes")
+ fcntl.fcntl(self.fd, 48, 1) # Darwin F_NOCACHE
+ fcntl.fcntl(self.fd, 45, 0) # Darwin F_RDAHEAD
+ # F_NOCACHE alone is insufficient: an unaligned Python bytes buffer
+ # makes macOS read surrounding sectors, corrupting address symbols.
+ page_size = os.sysconf("SC_PAGESIZE")
+ result = self.libc.posix_memalign(ctypes.byref(self.buffer), page_size, page_size)
+ if result:
+ raise OSError(result, os.strerror(result))
+ except BaseException:
+ os.close(self.fd)
+ raise
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+ def close(self):
+ if self.fd < 0:
+ return
+ self.libc.free(self.buffer)
+ self.buffer = ctypes.c_void_p()
+ os.close(self.fd)
+ self.fd = -1
+
+ def invalidate_cache(self):
+ """Evict existing cached pages before reading an ordinary status file."""
+ if self.fd < 0:
+ raise ValueError("channel is closed")
+ size = os.fstat(self.fd).st_size
+ if size == 0:
+ return
+ self.libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,
+ ctypes.c_int, ctypes.c_int, ctypes.c_longlong]
+ self.libc.mmap.restype = ctypes.c_void_p
+ self.libc.msync.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
+ self.libc.msync.restype = ctypes.c_int
+ self.libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]
+ self.libc.munmap.restype = ctypes.c_int
+ # PROT_READ | MAP_SHARED; never access the mapping itself.
+ address = self.libc.mmap(None, size, 1, 1, self.fd, 0)
+ if address == ctypes.c_void_p(-1).value:
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error))
+ try:
+ if self.libc.msync(address, size, 2) != 0: # MS_INVALIDATE
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error))
+ finally:
+ if self.libc.munmap(address, size) != 0:
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error))
+
+ def read_at(self, offset: int) -> bytes:
+ if self.fd < 0:
+ raise ValueError("channel is closed")
+ count = self.libc.pread(self.fd, self.buffer, 512, offset)
+ if count < 0:
+ error = ctypes.get_errno()
+ raise OSError(error, os.strerror(error))
+ return ctypes.string_at(self.buffer, count)
+
+
+
+def read_status_bytes(path: Path) -> bytes:
+ """Read status with the read-only, uncached macOS transport."""
+ if sys.platform == "darwin":
+ with _MacFile(path) as stream:
+ stream.invalidate_cache()
+ data = b""
+ for offset in range(0, 4096, 512):
+ block = stream.read_at(offset)
+ data += block
+ if len(block) < 512:
+ break
+ else:
+ with path.open("rb") as stream:
+ data = stream.read(4096)
+ return data
diff --git a/tests/test_keepalive.py b/tests/test_keepalive.py
new file mode 100644
index 0000000..85ff8ba
--- /dev/null
+++ b/tests/test_keepalive.py
@@ -0,0 +1,54 @@
+from unittest.mock import patch
+
+import pytest
+
+from sidepulse import keep_awake, status_reader
+
+
+def volume(tmp_path):
+ (tmp_path / "STATUS.TXT").write_text("legacy status\n")
+ return tmp_path
+
+
+def test_readonly_keepalive_reads_status(volume):
+ with patch.object(keep_awake.subprocess, "run") as run, patch.object(
+ status_reader, "read_status_bytes"
+ ) as read:
+ controller = keep_awake.KeepAwakeController(status_read_async=False)
+ assert controller.poke_status_file(volume / "LEDS.LED", now=0) == volume / "STATUS.TXT"
+ read.assert_called_once_with(volume / "STATUS.TXT")
+ run.assert_not_called()
+
+
+def test_keepalive_reads_status_without_firmware_validation(volume):
+ (volume / "STATUS.TXT").write_text("legacy status\n")
+ with patch.object(status_reader.sys, "platform", "linux"):
+ keep_awake.read_status_file(volume / "STATUS.TXT")
+ assert not (volume / "keepalive").exists()
+
+
+def test_keepalive_uses_uncached_mac_reader(volume):
+ from sidepulse import status_reader as read2me
+
+ with patch.object(status_reader.sys, "platform", "darwin"), patch.object(
+ read2me, "_MacFile"
+ ) as reader:
+ reader.return_value.__enter__.return_value.read_at.return_value = b"status"
+ keep_awake.read_status_file(volume / "STATUS.TXT")
+ reader.assert_called_once_with(volume / "STATUS.TXT")
+ reader.return_value.__enter__.return_value.invalidate_cache.assert_called_once_with()
+ reader.return_value.__enter__.return_value.read_at.assert_called_once_with(0)
+
+
+def test_keepalive_cache_invalidation_failure_prevents_read(volume):
+ from sidepulse import status_reader as read2me
+
+ with patch.object(status_reader.sys, "platform", "darwin"), patch.object(
+ read2me, "_MacFile"
+ ) as reader:
+ stream = reader.return_value.__enter__.return_value
+ stream.invalidate_cache.side_effect = OSError("invalidation failed")
+ with pytest.raises(OSError, match="invalidation failed"):
+ keep_awake.read_status_file(volume / "STATUS.TXT")
+ stream.read_at.assert_not_called()
diff --git a/tests/test_readonly_control.py b/tests/test_readonly_control.py
index bb73eba..6e11212 100644
--- a/tests/test_readonly_control.py
+++ b/tests/test_readonly_control.py
@@ -11,7 +11,7 @@ import pytest
from sidepulse import device_writer as writer
from sidepulse import readonly_control as readonly
from sidepulse import usb_control as usb
-from sidepulse import keep_awake
+from sidepulse import keep_awake, status_reader
@pytest.fixture
@@ -287,7 +287,7 @@ def test_writer_serializes_threads(volume):
def test_readonly_keepalive_reads_status(volume):
with patch.object(keep_awake.subprocess, "run") as run, patch.object(
- readonly, "read_status_bytes"
+ status_reader, "read_status_bytes"
) as read:
controller = keep_awake.KeepAwakeController(status_read_async=False)
assert controller.poke_status_file(volume / "LEDS.LED", now=0) == volume / "STATUS.TXT"
@@ -297,15 +297,15 @@ def test_readonly_keepalive_reads_status(volume):
def test_keepalive_reads_status_without_firmware_validation(volume):
(volume / "STATUS.TXT").write_text("legacy status\n")
- with patch.object(readonly.sys, "platform", "linux"):
+ with patch.object(status_reader.sys, "platform", "linux"):
keep_awake.read_status_file(volume / "STATUS.TXT")
assert not (volume / "keepalive").exists()
def test_keepalive_uses_uncached_mac_reader(volume):
- from sidepulse._vendor import read2me
+ from sidepulse import status_reader as read2me
- with patch.object(readonly.sys, "platform", "darwin"), patch.object(
+ with patch.object(status_reader.sys, "platform", "darwin"), patch.object(
read2me, "_MacFile"
) as reader:
reader.return_value.__enter__.return_value.read_at.return_value = b"status"
@@ -316,9 +316,9 @@ def test_keepalive_uses_uncached_mac_reader(volume):
def test_keepalive_cache_invalidation_failure_prevents_read(volume):
- from sidepulse._vendor import read2me
+ from sidepulse import status_reader as read2me
- with patch.object(readonly.sys, "platform", "darwin"), patch.object(
+ with patch.object(status_reader.sys, "platform", "darwin"), patch.object(
read2me, "_MacFile"
) as reader:
stream = reader.return_value.__enter__.return_value