runtime.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Gateway runtime wiring for the Teams meeting pipeline plugin."""
  2. from __future__ import annotations
  3. import asyncio
  4. import logging
  5. from typing import Any
  6. from gateway.config import Platform
  7. from plugins.teams_pipeline.pipeline import TeamsMeetingPipeline
  8. from plugins.teams_pipeline.store import TeamsPipelineStore, resolve_teams_pipeline_store_path
  9. from plugins.teams_pipeline.subscriptions import build_graph_client
  10. logger = logging.getLogger(__name__)
  11. # Teams platform settings mirrored into the pipeline's teams_delivery config (pipeline keys win).
  12. _DELIVERY_KEYS = ("incoming_webhook_url", "access_token", "team_id", "channel_id", "chat_id")
  13. def _teams_delivery_is_configured(teams_extra: dict[str, Any], teams_delivery: dict[str, Any]) -> bool:
  14. def pick(key: str) -> Any:
  15. return teams_delivery.get(key) or teams_extra.get(key)
  16. delivery_mode = str(teams_delivery.get("mode") or pick("delivery_mode") or "").strip().lower()
  17. if delivery_mode == "incoming_webhook":
  18. return bool(pick("incoming_webhook_url"))
  19. if delivery_mode == "graph":
  20. return bool(pick("chat_id") or (pick("team_id") and pick("channel_id")))
  21. return False
  22. def build_pipeline_runtime_config(gateway_config: Any) -> dict[str, Any]:
  23. """Pipeline knobs live under ``teams.extra.meeting_pipeline``; Teams delivery targets are
  24. mirrored from the Teams platform config so they are not configured twice."""
  25. teams_config = gateway_config.platforms.get(Platform("teams"))
  26. teams_extra = dict((teams_config.extra or {}) if teams_config else {})
  27. pipeline_config = dict(teams_extra.get("meeting_pipeline") or {})
  28. if teams_config and teams_config.enabled:
  29. teams_delivery = dict(pipeline_config.get("teams_delivery") or {})
  30. if delivery_mode := str(teams_extra.get("delivery_mode") or "").strip():
  31. teams_delivery["mode"] = delivery_mode
  32. for key in _DELIVERY_KEYS:
  33. value = teams_extra.get(key)
  34. if value not in {None, ""}:
  35. teams_delivery[key] = value
  36. if teams_delivery:
  37. teams_delivery["enabled"] = _teams_delivery_is_configured(teams_extra, teams_delivery)
  38. pipeline_config["teams_delivery"] = teams_delivery
  39. return pipeline_config
  40. def build_pipeline_runtime(gateway: Any) -> TeamsMeetingPipeline:
  41. teams_sender = None
  42. teams_config = gateway.config.platforms.get(Platform("teams"))
  43. pipeline_config = build_pipeline_runtime_config(gateway.config)
  44. if teams_config and teams_config.enabled and (pipeline_config.get("teams_delivery") or {}).get("enabled"):
  45. try:
  46. from plugins.platforms.teams.summary_writer import TeamsSummaryWriter
  47. except ImportError:
  48. logger.debug("TeamsSummaryWriter unavailable; Teams outbound delivery remains disabled until the adapter layer is present.")
  49. else:
  50. teams_sender = TeamsSummaryWriter(platform_config=teams_config)
  51. return TeamsMeetingPipeline(
  52. graph_client=build_graph_client(), store=TeamsPipelineStore(resolve_teams_pipeline_store_path()),
  53. config=pipeline_config, teams_sender=teams_sender,
  54. )
  55. def bind_gateway_runtime(gateway: Any) -> bool:
  56. """Attach the Teams pipeline runtime to the msgraph webhook adapter."""
  57. adapter = gateway.adapters.get(Platform.MSGRAPH_WEBHOOK)
  58. if adapter is None:
  59. return False
  60. if getattr(gateway, "_teams_pipeline_runtime", None) is not None:
  61. return True
  62. try:
  63. runtime = build_pipeline_runtime(gateway)
  64. except Exception as exc:
  65. # Without a runtime, notifications must still be acked (and dropped) so Graph does not retry-storm.
  66. gateway._teams_pipeline_runtime_error = str(exc)
  67. logger.warning(
  68. "Teams pipeline runtime unavailable: %s. Installing a drop-scheduler "
  69. "so Graph notifications ack cleanly without piling up unbound.", exc,
  70. )
  71. async def _drop(notification: dict[str, Any], event: Any) -> None:
  72. logger.debug("Dropping Graph notification because runtime is unavailable: id=%s resource=%s",
  73. notification.get("id"), notification.get("resource"))
  74. adapter.set_notification_scheduler(_drop)
  75. return False
  76. # Graph wants a prompt 202 once the work is durable: accept (persist the job) inside the request,
  77. # run the fetch/transcript/summary pipeline detached. An accept failure still fails the request.
  78. background = getattr(adapter, "_background_tasks", set())
  79. # Claim a job before scheduling its external effects: a no-id duplicate in one Graph batch
  80. # returns the same still-"received" job (run_job persists progress only once it runs).
  81. scheduled: set[str] = set()
  82. async def _schedule(notification: dict[str, Any], event: Any) -> None:
  83. job = runtime.create_job_from_notification(notification)
  84. if job.status != "received" or job.job_id in scheduled: # duplicate of a running or finished job
  85. return
  86. scheduled.add(job.job_id)
  87. task = asyncio.create_task(runtime.run_job(job.job_id))
  88. background.add(task)
  89. task.add_done_callback(background.discard)
  90. task.add_done_callback(lambda _task: scheduled.discard(job.job_id))
  91. adapter.set_notification_scheduler(_schedule)
  92. gateway._teams_pipeline_runtime = runtime
  93. gateway._teams_pipeline_runtime_error = None
  94. return True