|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | | -"""Thread-safe, time-bounded ring buffer for serialised ROS2 messages. |
| 15 | +"""Thread-safe, time-bounded ring buffers for serialised ROS2 messages. |
| 16 | +
|
| 17 | +Two implementations are provided: |
| 18 | +
|
| 19 | +* :class:`RingBuffer` – in-memory (default), uses a :class:`collections.deque`. |
| 20 | +* :class:`FileRingBuffer` – file-backed; only a small index is kept in RAM |
| 21 | + while message payloads are stored in a temporary file. Suitable for |
| 22 | + high-bandwidth topics such as camera images where RAM usage is a concern. |
| 23 | +
|
| 24 | +Both classes expose the same public API so they are interchangeable. |
16 | 25 |
|
17 | 26 | Kept in a separate module so it can be unit-tested without a ROS2 |
18 | 27 | installation. |
19 | 28 | """ |
20 | 29 |
|
| 30 | +import struct |
| 31 | +import tempfile |
21 | 32 | import threading |
22 | 33 | from collections import deque |
23 | 34 | from typing import List, Tuple |
@@ -71,3 +82,140 @@ def memory_bytes(self) -> int: |
71 | 82 | """Estimated total byte size of all buffered message payloads.""" |
72 | 83 | with self._lock: |
73 | 84 | return sum(len(d) for _, _, _, d in self._buf) |
| 85 | + |
| 86 | + |
| 87 | +class FileRingBuffer: |
| 88 | + """File-backed ring buffer that retains the last *duration_seconds* of data. |
| 89 | +
|
| 90 | + Message payloads are written to a temporary file so that RAM usage stays |
| 91 | + low regardless of payload size. Only a compact in-memory index |
| 92 | + ``(timestamp_ns, file_offset, record_size)`` is kept per message. |
| 93 | +
|
| 94 | + The temporary file is automatically removed when the buffer is garbage- |
| 95 | + collected or when :meth:`close` is called explicitly. |
| 96 | +
|
| 97 | + The public API is identical to :class:`RingBuffer`, making the two |
| 98 | + classes interchangeable. |
| 99 | + """ |
| 100 | + |
| 101 | + # Binary record header: timestamp_ns (int64 BE), topic_len (uint32 BE), |
| 102 | + # type_name_len (uint32 BE), data_len (uint32 BE) |
| 103 | + _HDR: struct.Struct = struct.Struct('>qIII') |
| 104 | + |
| 105 | + def __init__(self, duration_seconds: float) -> None: |
| 106 | + self._duration_ns: int = int(duration_seconds * 1_000_000_000) |
| 107 | + self._lock: threading.Lock = threading.Lock() |
| 108 | + # TemporaryFile is deleted automatically on close/GC |
| 109 | + self._tmpfile = tempfile.TemporaryFile() |
| 110 | + self._write_pos: int = 0 |
| 111 | + # Each entry: (timestamp_ns, file_offset, record_size_bytes) |
| 112 | + self._index: deque = deque() |
| 113 | + self._live_bytes: int = 0 # bytes occupied by non-purged records |
| 114 | + |
| 115 | + # ------------------------------------------------------------------ |
| 116 | + # Serialisation helpers |
| 117 | + # ------------------------------------------------------------------ |
| 118 | + |
| 119 | + def _pack( |
| 120 | + self, |
| 121 | + timestamp_ns: int, |
| 122 | + topic: str, |
| 123 | + type_name: str, |
| 124 | + data: bytes, |
| 125 | + ) -> bytes: |
| 126 | + tb = topic.encode() |
| 127 | + tnb = type_name.encode() |
| 128 | + hdr = self._HDR.pack(timestamp_ns, len(tb), len(tnb), len(data)) |
| 129 | + return hdr + tb + tnb + data |
| 130 | + |
| 131 | + def _unpack_at(self, offset: int) -> Tuple[int, str, str, bytes]: |
| 132 | + self._tmpfile.seek(offset) |
| 133 | + hdr_bytes = self._tmpfile.read(self._HDR.size) |
| 134 | + ts_ns, tl, tnl, dl = self._HDR.unpack(hdr_bytes) |
| 135 | + topic = self._tmpfile.read(tl).decode() |
| 136 | + type_name = self._tmpfile.read(tnl).decode() |
| 137 | + data = self._tmpfile.read(dl) |
| 138 | + return (ts_ns, topic, type_name, data) |
| 139 | + |
| 140 | + # ------------------------------------------------------------------ |
| 141 | + # Core operations |
| 142 | + # ------------------------------------------------------------------ |
| 143 | + |
| 144 | + def add( |
| 145 | + self, |
| 146 | + timestamp_ns: int, |
| 147 | + topic: str, |
| 148 | + type_name: str, |
| 149 | + data: bytes, |
| 150 | + ) -> None: |
| 151 | + """Append a message and evict entries outside the retention window.""" |
| 152 | + record = self._pack(timestamp_ns, topic, type_name, data) |
| 153 | + with self._lock: |
| 154 | + self._tmpfile.seek(self._write_pos) |
| 155 | + self._tmpfile.write(record) |
| 156 | + self._index.append((timestamp_ns, self._write_pos, len(record))) |
| 157 | + self._write_pos += len(record) |
| 158 | + self._live_bytes += len(record) |
| 159 | + self._purge(timestamp_ns) |
| 160 | + |
| 161 | + def _purge(self, now_ns: int) -> None: |
| 162 | + """Evict records older than the retention window (called under lock).""" |
| 163 | + if self._duration_ns <= 0: |
| 164 | + return |
| 165 | + cutoff = now_ns - self._duration_ns |
| 166 | + while self._index and self._index[0][0] < cutoff: |
| 167 | + _, _, size = self._index.popleft() |
| 168 | + self._live_bytes -= size |
| 169 | + # Reclaim disk space when dead bytes exceed live bytes |
| 170 | + dead = self._write_pos - self._live_bytes |
| 171 | + if self._index and dead > self._live_bytes: |
| 172 | + self._compact() |
| 173 | + |
| 174 | + def _compact(self) -> None: |
| 175 | + """Rewrite the temp file keeping only live records (called under lock).""" |
| 176 | + # Read all live raw records before modifying the file |
| 177 | + live_chunks: List[bytes] = [] |
| 178 | + for _ts, offset, size in self._index: |
| 179 | + self._tmpfile.seek(offset) |
| 180 | + live_chunks.append(self._tmpfile.read(size)) |
| 181 | + |
| 182 | + self._tmpfile.seek(0) |
| 183 | + self._tmpfile.truncate(0) |
| 184 | + new_pos: int = 0 |
| 185 | + new_index: deque = deque() |
| 186 | + for (ts_ns, _old_off, size), chunk in zip(self._index, live_chunks): |
| 187 | + self._tmpfile.write(chunk) |
| 188 | + new_index.append((ts_ns, new_pos, size)) |
| 189 | + new_pos += size |
| 190 | + self._tmpfile.flush() |
| 191 | + self._write_pos = new_pos |
| 192 | + self._live_bytes = new_pos |
| 193 | + self._index = new_index |
| 194 | + |
| 195 | + # ------------------------------------------------------------------ |
| 196 | + def snapshot(self) -> List[Tuple[int, str, str, bytes]]: |
| 197 | + """Return a point-in-time copy of all buffered messages.""" |
| 198 | + with self._lock: |
| 199 | + return [self._unpack_at(offset) for _, offset, _ in self._index] |
| 200 | + |
| 201 | + def size(self) -> int: |
| 202 | + """Number of messages currently in the buffer.""" |
| 203 | + with self._lock: |
| 204 | + return len(self._index) |
| 205 | + |
| 206 | + def memory_bytes(self) -> int: |
| 207 | + """Bytes occupied by live records in the backing file.""" |
| 208 | + with self._lock: |
| 209 | + return self._live_bytes |
| 210 | + |
| 211 | + # ------------------------------------------------------------------ |
| 212 | + def close(self) -> None: |
| 213 | + """Close and delete the backing temporary file.""" |
| 214 | + with self._lock: |
| 215 | + self._tmpfile.close() |
| 216 | + |
| 217 | + def __del__(self) -> None: |
| 218 | + try: |
| 219 | + self._tmpfile.close() |
| 220 | + except Exception: # noqa: BLE001 |
| 221 | + pass |
0 commit comments