subscriptions.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """Microsoft Graph subscription helpers for the Teams pipeline plugin."""
  2. from __future__ import annotations
  3. from datetime import datetime, timedelta, timezone, UTC
  4. from os import getenv
  5. from typing import Any
  6. from plugins.teams_pipeline.models import GraphSubscription, _parse_datetime
  7. from plugins.teams_pipeline.models import _serialize_datetime as _iso_z
  8. from plugins.teams_pipeline.store import TeamsPipelineStore
  9. from tools.microsoft_graph_auth import MicrosoftGraphTokenProvider
  10. from tools.microsoft_graph_client import MicrosoftGraphClient
  11. def build_graph_client() -> MicrosoftGraphClient:
  12. return MicrosoftGraphClient(MicrosoftGraphTokenProvider.from_env())
  13. def _utc_now() -> datetime:
  14. return datetime.now(UTC)
  15. def utc_timestamp(hours_from_now: int = 0, *, base: datetime | None = None) -> str:
  16. """Second-precision UTC ISO timestamp with a ``Z`` suffix (Graph's expirationDateTime format)."""
  17. return _iso_z(((base or _utc_now()) + timedelta(hours=hours_from_now)).replace(microsecond=0))
  18. def sync_graph_subscription_record(
  19. store: TeamsPipelineStore, subscription_payload: dict[str, Any], *, status: str | None = None, renewed: bool = False,
  20. ) -> dict[str, Any]:
  21. normalized = GraphSubscription.from_dict(subscription_payload).to_dict()
  22. if status is None:
  23. expiration = _parse_datetime(normalized.get("expiration_datetime"))
  24. status = "expired" if expiration and expiration <= _utc_now() else "active"
  25. normalized["status"] = status
  26. if renewed:
  27. normalized["latest_renewal_at"] = utc_timestamp()
  28. return store.upsert_subscription(normalized["subscription_id"], normalized)
  29. def expected_client_state(raw: str | None = None) -> str | None:
  30. if raw is None:
  31. raw = getenv("MSGRAPH_WEBHOOK_CLIENT_STATE", "")
  32. return str(raw or "").strip() or None
  33. def is_managed_subscription(store: TeamsPipelineStore, subscription_payload: dict[str, Any], *, expected_client_state_value: str | None) -> bool:
  34. """A subscription is ours if the store knows it or its clientState matches the configured one."""
  35. subscription_id = str(subscription_payload.get("subscription_id") or subscription_payload.get("id") or "").strip()
  36. if subscription_id and store.get_subscription(subscription_id):
  37. return True
  38. candidate_state = str(subscription_payload.get("client_state") or subscription_payload.get("clientState") or "").strip()
  39. return bool(expected_client_state_value and candidate_state == expected_client_state_value)
  40. async def maintain_graph_subscriptions(
  41. *, client: MicrosoftGraphClient, store: TeamsPipelineStore, renew_within_hours: int = 24, extend_hours: int = 24,
  42. dry_run: bool = False, client_state: str | None = None,
  43. ) -> dict[str, Any]:
  44. threshold_hours = max(1, int(renew_within_hours))
  45. extend_hours = max(1, int(extend_hours))
  46. managed_client_state = expected_client_state(client_state)
  47. now = _utc_now()
  48. remote_subscriptions = await client.collect_paginated("/subscriptions")
  49. remote_ids: set[str] = set()
  50. synced = 0
  51. renewed: list[dict[str, Any]] = []
  52. candidates: list[dict[str, Any]] = []
  53. skipped: list[dict[str, Any]] = []
  54. for raw in remote_subscriptions:
  55. if not isinstance(raw, dict):
  56. continue
  57. subscription_id = str(raw.get("id") or "").strip()
  58. if not subscription_id:
  59. continue
  60. def skip(reason: str, **extra: Any) -> None:
  61. skipped.append({"subscription_id": subscription_id, "reason": reason, **extra})
  62. if not is_managed_subscription(store, raw, expected_client_state_value=managed_client_state):
  63. skip("not_managed_by_teams_pipeline")
  64. continue
  65. remote_ids.add(subscription_id)
  66. try:
  67. sync_graph_subscription_record(store, raw)
  68. synced += 1
  69. except Exception as exc:
  70. skip(f"failed_to_sync_local_store: {exc}")
  71. continue
  72. expiration = _parse_datetime(raw.get("expirationDateTime"))
  73. if expiration is None:
  74. skip("missing_expiration")
  75. continue
  76. seconds_until_expiry = int((expiration - now).total_seconds())
  77. if seconds_until_expiry < 0:
  78. store.upsert_subscription(subscription_id, {"status": "expired", "expiration_datetime": _iso_z(expiration)})
  79. skip("already_expired", expiration_datetime=_iso_z(expiration))
  80. continue
  81. if seconds_until_expiry > threshold_hours * 3600:
  82. skip("not_due", expires_in_seconds=seconds_until_expiry)
  83. continue
  84. new_expiration = utc_timestamp(extend_hours, base=max(now, expiration))
  85. candidate = {"subscription_id": subscription_id, "resource": raw.get("resource"),
  86. "current_expiration": _iso_z(expiration), "new_expiration": new_expiration}
  87. candidates.append(candidate)
  88. if dry_run:
  89. continue
  90. patched = await client.patch_json(f"/subscriptions/{subscription_id}", json_body={"expirationDateTime": new_expiration})
  91. merged = {**raw, **(patched or {}), "id": subscription_id, "expirationDateTime": new_expiration}
  92. sync_graph_subscription_record(store, merged, status="active", renewed=True)
  93. renewed.append({**candidate, "result": patched})
  94. # Locally-known subscriptions Graph no longer reports are flagged, never deleted.
  95. for subscription_id in store.list_subscriptions():
  96. if subscription_id not in remote_ids:
  97. store.upsert_subscription(subscription_id, {"status": "missing_remote", "last_seen_missing_remote_at": utc_timestamp()})
  98. return {
  99. "success": True, "dry_run": bool(dry_run), "store_path": str(store.path),
  100. "remote_subscription_count": len(remote_subscriptions), "synced_subscription_count": synced,
  101. "candidate_count": len(candidates), "renewed_count": len(renewed),
  102. "threshold_hours": threshold_hours, "extend_hours": extend_hours,
  103. "candidates": candidates, "renewed": renewed, "skipped": skipped,
  104. }