Write/overwrite the pointer for ``working_dir``. ``created_at_ms`` defaults to the current time on first write; callers preserving a pre-existing pointer's identity should pass its ``created_at_ms`` so the field doesn't reset on every update. Writes through a tmpfile + ``os.replace
(
working_dir: str, *,
bridge_id: str,
environment_id: str,
session_id: str | None,
machine_name: str,
created_at_ms: int | None = None,
)
| 193 | |
| 194 | |
| 195 | def write_pointer( |
| 196 | working_dir: str, *, |
| 197 | bridge_id: str, |
| 198 | environment_id: str, |
| 199 | session_id: str | None, |
| 200 | machine_name: str, |
| 201 | created_at_ms: int | None = None, |
| 202 | ) -> None: |
| 203 | """Write/overwrite the pointer for ``working_dir``. |
| 204 | |
| 205 | ``created_at_ms`` defaults to the current time on first write; |
| 206 | callers preserving a pre-existing pointer's identity should pass |
| 207 | its ``created_at_ms`` so the field doesn't reset on every update. |
| 208 | |
| 209 | Writes through a tmpfile + ``os.replace`` for atomicity — a crash |
| 210 | during the write cannot leave a half-written pointer that |
| 211 | ``read_pointer`` then parses incorrectly. |
| 212 | """ |
| 213 | path = _pointer_path(working_dir) |
| 214 | now = _now_ms() |
| 215 | pointer = BridgePointer( |
| 216 | bridge_id=bridge_id, |
| 217 | environment_id=environment_id, |
| 218 | session_id=session_id, |
| 219 | machine_name=machine_name, |
| 220 | dir=working_dir, |
| 221 | created_at_ms=created_at_ms if created_at_ms is not None else now, |
| 222 | updated_at_ms=now, |
| 223 | ) |
| 224 | try: |
| 225 | os.makedirs(os.path.dirname(path), exist_ok=True) |
| 226 | except OSError as err: |
| 227 | logger.warning( |
| 228 | '[bridge:pointer] mkdir(%s) failed: %s — pointer not written', |
| 229 | os.path.dirname(path), err, |
| 230 | ) |
| 231 | return |
| 232 | tmp_path = f'{path}.tmp' |
| 233 | try: |
| 234 | with open(tmp_path, 'w', encoding='utf-8') as fh: |
| 235 | json.dump(pointer.to_json(), fh, indent=2) |
| 236 | os.replace(tmp_path, path) |
| 237 | except OSError as err: |
| 238 | logger.warning( |
| 239 | '[bridge:pointer] write %s failed: %s — pointer not written', |
| 240 | path, err, |
| 241 | ) |
| 242 | # Best-effort cleanup of the tmpfile. |
| 243 | try: |
| 244 | os.unlink(tmp_path) |
| 245 | except OSError: |
| 246 | pass |
| 247 | |
| 248 | |
| 249 | def clear_pointer(working_dir: str) -> None: |