live.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """Live operations, one open per (profile, session), found by ``op_id``. The RPC layer reads and
  2. drives operations through here; the tool thread that minted one closes it on settle.
  3. The profile is part of the key: two multiplexed profiles can carry the same timestamp-based
  4. session key, and each side (the tool thread under the turn's profile override, the RPC under the
  5. session's profile scope) resolves it through ``hermes_home_key``."""
  6. from __future__ import annotations
  7. import logging
  8. import threading
  9. from typing import Dict, Optional, Tuple
  10. from hermes_constants import get_process_hermes_home, hermes_home_key
  11. from tools.connectors.operation import ConnectionOperation
  12. logger = logging.getLogger(__name__)
  13. class OperationAlreadyOpen(RuntimeError):
  14. def __init__(self, existing: ConnectionOperation):
  15. super().__init__(f"session {existing.session_key!r} already has operation {existing.op_id} open")
  16. self.existing = existing
  17. _open: dict[tuple[str, str], ConnectionOperation] = {}
  18. _lock = threading.Lock()
  19. def _profile_key(profile_home: Optional[str]) -> str:
  20. """A session record names its profile home only for a non-default profile; the tool thread sees
  21. the same home through its turn override, and the default profile through the process home."""
  22. return hermes_home_key(profile_home or get_process_hermes_home())
  23. def _key(session_key: str, profile_home: Optional[str]) -> tuple[str, str]:
  24. return _profile_key(profile_home), session_key
  25. def open(operation: ConnectionOperation) -> None:
  26. operation.profile_key = hermes_home_key()
  27. key = (operation.profile_key, operation.session_key)
  28. with _lock:
  29. existing = _open.get(key)
  30. if existing is not None and not existing.settled:
  31. raise OperationAlreadyOpen(existing)
  32. _open[key] = operation
  33. logger.info("connection op %s opened: %s", operation.op_id,
  34. ", ".join(f"{t.kind}:{t.name}:{t.action}" for t in operation.targets))
  35. def current(session_key: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
  36. with _lock:
  37. operation = _open.get(_key(session_key, profile_home))
  38. return operation if operation is not None and not operation.settled else None
  39. def get(session_key: str, op_id: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
  40. with _lock:
  41. operation = _open.get(_key(session_key, profile_home))
  42. return operation if operation is not None and operation.op_id == op_id else None
  43. def get_by_op_id(op_id: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
  44. profile_key = _profile_key(profile_home)
  45. with _lock:
  46. return next((operation for (key, _), operation in _open.items()
  47. if key == profile_key and operation.op_id == op_id and not operation.settled), None)
  48. def find_target(name: str, *, alias: Optional[str] = None, repair_id: Optional[str] = None,
  49. profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
  50. """The open operation connecting this account: the connector ``name`` and the same ``alias`` and
  51. repaired account id, so an open operation for one account is never reused for another of the same app."""
  52. profile_key = _profile_key(profile_home)
  53. with _lock:
  54. return next((operation for (key, _), operation in _open.items()
  55. if key == profile_key and not operation.settled
  56. and (target := operation.target(name)) is not None and target.kind == "connector"
  57. and target.alias == alias and target.repair_id == repair_id), None)
  58. def close(operation: ConnectionOperation) -> None:
  59. key = (operation.profile_key, operation.session_key)
  60. with _lock:
  61. if _open.get(key) is operation:
  62. del _open[key]
  63. def reset_for_tests() -> None:
  64. with _lock:
  65. _open.clear()