account.py 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import annotations
  2. import contextvars
  3. import threading
  4. import uuid
  5. from dataclasses import dataclass, field
  6. from tools.connectors import live
  7. from tools.connectors import managed
  8. from tools.connectors.operation import ConnectionOperation, Target
  9. from tools.connectors.run import drive_operation
  10. _PREPARE_WAIT_SECONDS = 31.0
  11. _start_lock = threading.Lock()
  12. @dataclass
  13. class AccountOperationStart:
  14. operation: ConnectionOperation
  15. started: bool
  16. done: threading.Event = field(default_factory=threading.Event)
  17. failed: bool = False
  18. def _matching_open_operation(names: list[str], *, alias: str | None, repair_id: str | None,
  19. profile_home: str | None) -> ConnectionOperation | None:
  20. matches = [live.find_target(name, alias=alias, repair_id=repair_id, profile_home=profile_home) for name in names]
  21. first = next((operation for operation in matches if operation is not None), None)
  22. if first is None:
  23. return None
  24. if any(operation is not first for operation in matches):
  25. raise ValueError("requested connectors do not share one open operation")
  26. return first
  27. def find_or_start_operation(
  28. names: list[str],
  29. *,
  30. action: str,
  31. profile_home: str | None,
  32. alias: str | None = None,
  33. repair_id: str | None = None,
  34. initiator: str | None = None,
  35. ) -> AccountOperationStart:
  36. """``alias`` names the one account of ``names[0]`` to connect; ``repair_id`` names the existing
  37. account a reconnect repairs. The caller passes one name with either. ``initiator`` goes on the
  38. connect request; none leaves the gateway to record it as unknown."""
  39. with _start_lock:
  40. if operation := _matching_open_operation(names, alias=alias, repair_id=repair_id, profile_home=profile_home):
  41. return AccountOperationStart(operation=operation, started=False)
  42. operation = ConnectionOperation(
  43. [Target(name, "connector", action, alias=alias, repair_id=repair_id) for name in names],
  44. session_key=f"account:{uuid.uuid4().hex}",
  45. )
  46. started = AccountOperationStart(operation=operation, started=True)
  47. context = contextvars.copy_context()
  48. thread = threading.Thread(
  49. target=lambda: context.run(_run, started, action, initiator),
  50. daemon=True,
  51. name="connector-account-operation",
  52. )
  53. try:
  54. live.open(operation)
  55. thread.start()
  56. except Exception:
  57. live.close(operation)
  58. raise
  59. return started
  60. def _run(start: AccountOperationStart, action: str, initiator: str | None) -> None:
  61. from hermes_logging import clear_session_context, set_session_context
  62. # Tag this thread's log lines with the operation, the way a turn thread carries its session.
  63. set_session_context(start.operation.session_key)
  64. try:
  65. drive_operation(
  66. start.operation,
  67. managed.managed_kind(managed.managed_client(creates_guest=True, initiator=initiator), action, force=False),
  68. connection_callback=lambda _payload: start.done.set(),
  69. tick_seconds=managed.WATCH_TICK_SECONDS,
  70. with_urls_in_result=False,
  71. )
  72. except Exception:
  73. live.close(start.operation)
  74. start.failed = True
  75. finally:
  76. start.done.set()
  77. clear_session_context()
  78. def wait_for_prepare(start: AccountOperationStart) -> bool:
  79. return start.done.wait(_PREPARE_WAIT_SECONDS)