| 217 | |
| 218 | |
| 219 | class CLISessionOrchestrator: |
| 220 | def __init__(self, generator, writer, reader, sweeper): |
| 221 | self._generator = generator |
| 222 | self._writer = writer |
| 223 | self._reader = reader |
| 224 | self._sweeper = sweeper |
| 225 | |
| 226 | self._sweep_cache() |
| 227 | |
| 228 | @cached_property |
| 229 | def cache_key(self): |
| 230 | return self._generator.generate_cache_key(self._host_id, self._tty) |
| 231 | |
| 232 | @cached_property |
| 233 | def _session_id(self): |
| 234 | return self._generator.generate_session_id( |
| 235 | self._host_id, self._tty, self._timestamp |
| 236 | ) |
| 237 | |
| 238 | @cached_property |
| 239 | def session_id(self): |
| 240 | if (cached_data := self._reader.read(self.cache_key)) is not None: |
| 241 | # Cache hit, but session id is expired. Generate new id and update. |
| 242 | if ( |
| 243 | cached_data.timestamp + _SESSION_LENGTH_SECONDS |
| 244 | < self._timestamp |
| 245 | ): |
| 246 | cached_data.session_id = self._session_id |
| 247 | # Always update the timestamp to last used. |
| 248 | cached_data.timestamp = self._timestamp |
| 249 | self._writer.write(cached_data) |
| 250 | return cached_data.session_id |
| 251 | # Cache miss, generate and write new record. |
| 252 | session_id = self._session_id |
| 253 | session_data = CLISessionData( |
| 254 | self.cache_key, session_id, self._timestamp |
| 255 | ) |
| 256 | self._writer.write(session_data) |
| 257 | return session_id |
| 258 | |
| 259 | @cached_property |
| 260 | def _tty(self): |
| 261 | # os.ttyname is only available on Unix platforms. |
| 262 | if is_windows: |
| 263 | return |
| 264 | try: |
| 265 | return os.ttyname(sys.stdin.fileno()) |
| 266 | except (OSError, io.UnsupportedOperation): |
| 267 | # Standard input was redirected to a pseudofile. |
| 268 | # This can happen when running tests on IDEs or |
| 269 | # running scripts with redirected input, etc. |
| 270 | return |
| 271 | |
| 272 | @cached_property |
| 273 | def _host_id(self): |
| 274 | return self._reader.read_host_id() |
| 275 | |
| 276 | @cached_property |
no outgoing calls