Просмотр исходного кода

refactor(ita): use framework error categories

zhangweijp 2 месяцев назад
Родитель
Сommit
e98808182c
1 измененных файлов с 109 добавлено и 109 удалено
  1. 109 109
      plugins/ita_plugin.py

+ 109 - 109
plugins/ita_plugin.py

@@ -20,7 +20,7 @@ from DrissionPage import ChromiumPage
 import vs_plg as _ita_host
 from vs_plg import IVSPlg
 from vs_types import (
-    AvailabilityStatus, BizLogicError,
+    AvailabilityStatus, BizLogicError, NotFoundError,
     DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
     SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
 )
@@ -325,18 +325,25 @@ TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
 DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
 
 
-class CalendarGateError(RuntimeError): pass
-class CalendarAuthenticationExpiredError(CalendarGateError): pass
-class CalendarRateLimitedError(CalendarGateError): pass
-class CalendarAccessDeniedError(CalendarGateError): pass
-class CalendarTransientError(CalendarGateError): pass
-class CalendarBookError(CalendarGateError): pass
+# Compatibility names for older diagnostics/tests. Runtime code raises the
+# framework exceptions directly so the host can apply its standard policy.
+CalendarGateError = BizLogicError
+CalendarAuthenticationExpiredError = SessionExpiredOrInvalidError
+CalendarRateLimitedError = RateLimiteddError
+CalendarAccessDeniedError = PermissionDeniedError
+CalendarTransientError = BizLogicError
+CalendarBookError = BizLogicError
 
 
 def same_origin_path(raw_url):
-    parsed = urlparse(str(raw_url or ""))
-    if parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it":
-        raise CalendarGateError("Italy request left the expected origin")
+    try:
+        parsed = urlparse(str(raw_url or ""))
+        port = parsed.port
+    except ValueError:
+        raise BizLogicError("Italy request left the expected origin") from None
+    if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
+            or port not in (None, 443)):
+        raise BizLogicError("Italy request left the expected origin")
     return parsed.path
 
 
@@ -374,9 +381,11 @@ selected = Boolean(candidateReady && slot.classList.contains('act'));
 return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
 """
 def _runtime_id(value):
+    if value is None or isinstance(value, bool):
+        raise BizLogicError("Italy Calendar service id is invalid")
     value = str(value).strip()
-    if not value or len(value) > 128:
-        raise CalendarBookError("Italy Calendar service id is invalid")
+    if not re.fullmatch(r"[1-9]\d{0,127}", value):
+        raise BizLogicError("Italy Calendar service id is invalid")
     return value
 
 
@@ -384,55 +393,50 @@ def _request_day(value):
     try:
         return date.fromisoformat(str(value))
     except ValueError:
-        raise CalendarBookError("Italy Calendar date format changed") from None
+        raise BizLogicError("Italy Calendar date format changed") from None
 
 
 def read_calendar_context(page):
     if same_origin_path(page.url) != CALENDAR_PATH:
-        raise CalendarBookError("Italy Calendar page is not current")
+        raise BizLogicError("Italy Calendar page is not current")
     raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
     if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
-        raise CalendarBookError("Italy Calendar context is not ready")
+        raise BizLogicError("Italy Calendar context is not ready")
     return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
 
-
-def read_calendar_service(page):
-    return read_calendar_context(page)[0]
-
-
 def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
     deadline = time.monotonic() + timeout
     while time.monotonic() < deadline:
         if session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         try:
-            service = read_calendar_service(page)
-        except CalendarBookError:
+            service = read_calendar_context(page)[0]
+        except BizLogicError:
             time.sleep(0.1)
             continue
         if expected_service and service != _runtime_id(expected_service):
-            raise CalendarBookError("Italy Calendar service changed")
+            raise BizLogicError("Italy Calendar service changed")
         return service
-    raise CalendarBookError("Italy Calendar service did not initialize")
+    raise BizLogicError("Italy Calendar service did not initialize")
 
 
 def _calendar_post(page, path, payload, parser):
     response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
     status, host = response.status_code, urlparse(str(response.url or "")).hostname
     if host == "iam.esteri.it" or status == 401:
-        raise CalendarAuthenticationExpiredError("Italy Calendar authentication expired")
+        raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
     if status == 403:
-        raise CalendarAccessDeniedError("Italy Calendar access denied")
+        raise PermissionDeniedError("Italy Calendar access denied")
     if status == 429:
-        raise CalendarRateLimitedError("Italy Calendar rate limited")
+        raise RateLimiteddError("Italy Calendar rate limited")
     if status in {0, 408, 502, 503, 504}:
-        raise CalendarTransientError("Italy Calendar temporarily unavailable")
+        raise BizLogicError("Italy Calendar temporarily unavailable")
     if status != 200 or same_origin_path(response.url) != path:
-        raise CalendarGateError("Italy Calendar returned an unexpected response")
+        raise BizLogicError("Italy Calendar returned an unexpected response")
     try:
         return parser(response.text)
     except ItaProtocolError as exc:
-        raise CalendarGateError(f"Italy Calendar response rejected ({exc.code})") from exc
+        raise BizLogicError(f"Italy Calendar response rejected ({exc.code})") from exc
 
 
 def fetch_calendar_month(page, service, selected_day):
@@ -451,7 +455,7 @@ def fetch_calendar_slots(page, service, selected_day):
         parse_time_slots,
     )
     if any(slot.day != selected_day for slot in slots):
-        raise CalendarBookError("Italy Calendar returned slots for another day")
+        raise BizLogicError("Italy Calendar returned slots for another day")
     return slots
 
 
@@ -477,7 +481,7 @@ def scan_until_first_available_month(
 def click_next_month(page, *, timeout=10, diagnostic=None):
     control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
     if not control:
-        raise CalendarBookError("Italy Calendar next-month control is unavailable")
+        raise NotFoundError("Italy Calendar next-month control is unavailable")
     control.click(by_js=True)
 
 
@@ -488,7 +492,7 @@ def _snapshot(page, mode, service, day, candidate=None, click=False):
         candidate.time_label, candidate.slots_free, click,
     )
     if not isinstance(raw, dict) or not raw.get("contextReady") or raw.get("candidateCount") != 1:
-        raise CalendarBookError("Italy Calendar selection context changed")
+        raise BizLogicError("Italy Calendar selection context changed")
     return raw
 
 
@@ -496,7 +500,7 @@ def verify_precommit_selection(page, *, runtime_service, candidate):
     raw = _snapshot(
         page, "slot", runtime_service, candidate.day, candidate, False)
     if not raw.get("candidateReady") or not raw.get("selected"):
-        raise CalendarBookError("Italy Calendar selected slot changed")
+        raise BizLogicError("Italy Calendar selected slot changed")
     return candidate
 
 
@@ -512,7 +516,7 @@ def select_slot_before_final(
     _snapshot(page, "date", runtime_service, target_day, click=True)
     while time.monotonic() < deadline:
         if session_is_current and session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         date_state = _snapshot(page, "date", runtime_service, target_day)
         slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
         if date_state.get("selected") and slot_state.get("candidateReady"):
@@ -521,7 +525,7 @@ def select_slot_before_final(
             return verify_precommit_selection(
                 page, runtime_service=runtime_service, candidate=candidate)
         time.sleep(0.1)
-    raise CalendarBookError("Italy Calendar slot did not finish loading")
+    raise BizLogicError("Italy Calendar slot did not finish loading")
 
 
 def book_date_preferences(user_inputs):
@@ -531,9 +535,9 @@ def book_date_preferences(user_inputs):
         try:
             values.append(date.fromisoformat(user_inputs.get(key, default)))
         except (AttributeError, TypeError, ValueError):
-            raise CalendarBookError(f"Italy {key} must use YYYY-MM-DD") from None
+            raise BizLogicError(f"Italy {key} must use YYYY-MM-DD") from None
     if values[0] > values[1]:
-        raise CalendarBookError("Italy date preference is inverted")
+        raise BizLogicError("Italy date preference is inverted")
     return tuple(values)
 
 
@@ -546,14 +550,14 @@ def _move_to_month(page, service, target, timeout):
         while time.monotonic() < deadline:
             actual_service, current = read_calendar_context(page)
             if actual_service != service:
-                raise CalendarBookError("Italy Calendar service changed")
+                raise BizLogicError("Italy Calendar service changed")
             if (current.year, current.month) == expected:
                 break
             time.sleep(0.1)
         else:
-            raise CalendarBookError("Italy Calendar month did not load")
+            raise BizLogicError("Italy Calendar month did not load")
     if (current.year, current.month) != target:
-        raise CalendarBookError("Italy Calendar cannot navigate backwards")
+        raise BizLogicError("Italy Calendar cannot navigate backwards")
 
 
 def recheck_calendar_before_final(
@@ -564,7 +568,7 @@ def recheck_calendar_before_final(
     service, anchor = read_calendar_context(page)
     for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
         if session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         if index and month_click_interval_seconds:
             time.sleep(month_click_interval_seconds)
         inventory = fetch_calendar_month(page, service, month_start)
@@ -600,7 +604,7 @@ def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VS
         prepared = plugin._require_calendar_context(route, role="book", username=username)
         if (not username or not isinstance(slot, SlotCandidate)
                 or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
-            raise CalendarBookError("Italy final context is not current")
+            raise BizLogicError("Italy final context is not current")
         verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
         response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
             "idCalendarioGiornaliero": slot.daily_calendar_id,
@@ -632,7 +636,7 @@ _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", L
 
 def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
     if not route.booking_type or not route.purpose:
-        raise CalendarGateError("Italy route is missing form controls")
+        raise BizLogicError("Italy route is missing form controls")
     config = {"path": booking_path, "booking": asdict(route.booking_type),
               "purpose": asdict(route.purpose)}
     return f"""
@@ -667,16 +671,16 @@ return {{
 
 def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
     if type(after_otp) is not bool or type(allow_pending) is not bool:
-        raise CalendarGateError("Italy booking preflight policy is invalid")
+        raise BizLogicError("Italy booking preflight policy is invalid")
     if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
             "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
-        raise CalendarGateError("Italy booking form structure changed")
+        raise BizLogicError("Italy booking form structure changed")
     if raw["otpValuePresent"] is not after_otp:
-        raise CalendarGateError("Italy booking OTP stage changed")
+        raise BizLogicError("Italy booking OTP stage changed")
     ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
              raw["turnstileReady"] and raw["avantiEnabled"])
     if not allow_pending and not ready:
-        raise CalendarGateError("Italy booking verification is not ready")
+        raise BizLogicError("Italy booking verification is not ready")
 
 
 def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
@@ -701,20 +705,20 @@ def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
     reason = ("form_pending" if not raw or not raw["formReady"] else
               "otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
               "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
-    raise CalendarGateError(f"Italy booking verification timed out: {reason}")
+    raise BizLogicError(f"Italy booking verification timed out: {reason}")
 
 
 def _element_or_fail(page, selector):
     element = page.ele(selector, timeout=5)
     if not element:
-        raise CalendarGateError(f"Italy booking element is missing: {selector}")
+        raise NotFoundError(f"Italy booking element is missing: {selector}")
     return element
 
 
 def _read_manual_otp():
     value = input("Italy booking OTP: ").strip()
     if not re.fullmatch(r"[0-9]{4,12}", value):
-        raise CalendarGateError("Italy OTP format rejected")
+        raise BizLogicError("Italy OTP format rejected")
     return value
 
 
@@ -723,14 +727,14 @@ def _enter_otp(plugin, otp):
     plugin.mouse.human_click_ele(field)
     field.input(otp, clear=True)
     if field.run_js("return this.value === arguments[0];", otp) is not True:
-        raise CalendarGateError("Italy OTP write failed")
+        raise BizLogicError("Italy OTP write failed")
 
 
 def validate_cloud_otp_environment(mail_config, recipient):
     if not isinstance(mail_config, OtpMailConfig):
-        raise CalendarGateError("Italy OTP mail configuration is missing")
+        raise BizLogicError("Italy OTP mail configuration is missing")
     if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
-        raise CalendarGateError("Italy OTP recipient is invalid")
+        raise BizLogicError("Italy OTP recipient is invalid")
     mail_config.mailbox_for(recipient)
     return recipient.strip()
 
@@ -740,7 +744,7 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
     try:
         datetime.strptime(sent_at, _SENT_AT_FORMAT)
     except (TypeError, ValueError):
-        raise CalendarGateError("Italy OTP sent time is invalid") from None
+        raise BizLogicError("Italy OTP sent time is invalid") from None
     try:
         body = (api or VSCloudApi.Instance()).fetch_mail_content(
             email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
@@ -748,9 +752,25 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
             sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
         )
         return parse_otp_body(body)
-    except Exception as exc:
-        message = "not permitted" if isinstance(exc, PermissionDeniedError) else "read failed"
-        raise CalendarGateError(f"Italy OTP mailbox {message}") from None
+    except ItaProtocolError as exc:
+        raise BizLogicError(f"Italy OTP body invalid ({exc.code})") from None
+    except PermissionDeniedError:
+        raise PermissionDeniedError("Italy OTP mailbox not permitted") from None
+    except SessionExpiredOrInvalidError:
+        raise SessionExpiredOrInvalidError("Italy OTP mailbox session expired") from None
+    except RateLimiteddError:
+        raise RateLimiteddError("Italy OTP mailbox rate limited") from None
+    except NotFoundError:
+        raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
+    except BizLogicError as exc:
+        status = re.search(r"\bHTTP Error (\d{3})\b", str(getattr(exc, "message", "")))
+        if status and int(status.group(1)) == 404:
+            raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
+        if status and int(status.group(1)) in {408, 502, 503, 504}:
+            raise BizLogicError("Italy OTP mailbox provider timed out") from None
+        raise BizLogicError("Italy OTP mailbox read failed") from None
+    except Exception:
+        raise BizLogicError("Italy OTP mailbox read failed") from None
 
 
 def _wait_for_calendar(page, timeout=30):
@@ -760,7 +780,7 @@ def _wait_for_calendar(page, timeout=30):
             page.wait.doc_loaded()
             return
         time.sleep(0.25)
-    raise CalendarGateError("Italy AVANTI did not reach Calendar")
+    raise BizLogicError("Italy AVANTI did not reach Calendar")
 
 
 def prepare_calendar(plugin, route, *, role):
@@ -776,7 +796,7 @@ def prepare_calendar(plugin, route, *, role):
 
     def current(path):
         if plugin.page is not page or same_origin_path(page.url) != path:
-            raise CalendarGateError("Italy preparation page changed")
+            raise SessionExpiredOrInvalidError("Italy preparation page changed")
 
     def click(selector):
         current(booking_path)
@@ -814,9 +834,10 @@ SERVICES_PROBE_QUERY_MODE = "services_probe"
 CALENDAR_QUERY_MODE = "calendar"
 
 
-class ItaAuthenticationChallengeError(BizLogicError): pass
-class ItaTargetServiceLinkMissingError(BizLogicError): pass
-class ItaCalendarTransientError(BizLogicError): pass
+# Compatibility names retained for callers of older Italy diagnostics.
+ItaAuthenticationChallengeError = PermissionDeniedError
+ItaTargetServiceLinkMissingError = NotFoundError
+ItaCalendarTransientError = BizLogicError
 
 
 @dataclass(frozen=True, repr=False, eq=False)
@@ -842,7 +863,7 @@ class ItaLoginFlow(BaseFlow):
 
     @guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
     def radware(self):
-        raise ItaAuthenticationChallengeError(
+        raise PermissionDeniedError(
             "Italy authentication requires Radware browser validation; automatic retry is disabled")
 
     @guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
@@ -854,7 +875,7 @@ class ItaLoginFlow(BaseFlow):
     @guard(predicate=lambda f: any(value in f.page.html for value in (
         "Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
     def blocked(self):
-        raise ItaAuthenticationChallengeError("Italy authentication was blocked; automatic retry is disabled")
+        raise PermissionDeniedError("Italy authentication was blocked; automatic retry is disabled")
 
     @guard(predicate=lambda f: any(value in f.page.html for value in (
         "502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
@@ -987,7 +1008,7 @@ class ItaPlugin(IVSPlg):
         try:
             self._prepared_calendar = _PreparedCalendar(
                 self.config.account.username.strip().casefold(), route.routing_key,
-                read_calendar_service(self.page), self.page.tab_id, role)
+                read_calendar_context(self.page)[0], self.page.tab_id, role)
         except Exception:
             self._prepared_calendar = None
             raise BizLogicError("Italy Calendar identity is unavailable") from None
@@ -995,7 +1016,7 @@ class ItaPlugin(IVSPlg):
     def _require_calendar_context(self, route, *, role, username=None):
         if not self._calendar_context_matches(route, role=role, username=username):
             raise BizLogicError("Italy Calendar Session changed")
-        if read_calendar_service(self.page) != self._prepared_calendar.runtime_service:
+        if read_calendar_context(self.page)[0] != self._prepared_calendar.runtime_service:
             raise BizLogicError("Italy Calendar service changed")
         return self._prepared_calendar
 
@@ -1003,21 +1024,6 @@ class ItaPlugin(IVSPlg):
         self.is_healthy = False
         self._prepared_calendar = None
 
-    def _calendar_failure(self, exc, role):
-        self._prepared_calendar = None
-        kinds = (
-            (CalendarAuthenticationExpiredError, SessionExpiredOrInvalidError, "Session expired"),
-            (CalendarRateLimitedError, RateLimiteddError, "rate limited"),
-            (CalendarAccessDeniedError, PermissionDeniedError, "access denied"),
-            (CalendarTransientError, ItaCalendarTransientError, "temporarily unavailable"),
-        )
-        for source, target, message in kinds:
-            if isinstance(exc, source):
-                if role == "Query" or source is CalendarAuthenticationExpiredError:
-                    self.is_healthy = False
-                return target(f"Italy {role} {message}")
-        return BizLogicError(f"Italy {role} failed: {exc}")
-
     def keep_alive(self):
         pass
 
@@ -1063,18 +1069,15 @@ class ItaPlugin(IVSPlg):
         if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
             raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
         route = self._resolve_route(apt_type)
-        try:
-            if same_origin_path(self.page.url) != CALENDAR_PATH:
-                entry = self._enter_service(apt_type, route=route)
-                if not entry.success:
-                    return entry
-                self._reset_calendar_state()
-                prepare_calendar(self, route, role="query")
-            self._require_calendar_context(route, role="query")
-            probes = scan_until_first_available_month(
-                self.page, lookahead_months=route.lookahead_months, log=self._log)
-        except CalendarGateError as exc:
-            raise self._calendar_failure(exc, "Query") from None
+        if same_origin_path(self.page.url) != CALENDAR_PATH:
+            entry = self._enter_service(apt_type, route=route)
+            if not entry.success:
+                return entry
+            self._reset_calendar_state()
+            prepare_calendar(self, route, role="query")
+        self._require_calendar_context(route, role="query")
+        probes = scan_until_first_available_month(
+            self.page, lookahead_months=route.lookahead_months, log=self._log)
         available = available_calendar_days(probes[-1])
         if not available:
             return VSQueryResult(
@@ -1097,7 +1100,7 @@ class ItaPlugin(IVSPlg):
             raise BizLogicError("Italy service list is unavailable")
         link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
         if not link:
-            raise ItaTargetServiceLinkMissingError(f"Italy service link is missing: {booking_path}")
+            raise NotFoundError(f"Italy service link is missing: {booking_path}")
         self.mouse.human_click_ele(link)
         self.page.wait.load_start()
         self.page.wait.doc_loaded()
@@ -1132,19 +1135,16 @@ class ItaPlugin(IVSPlg):
             if not entry.success:
                 return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
             prepare_calendar(self, route, role="book")
-        try:
-            start, end = book_date_preferences(inputs)
-            slot = recheck_calendar_before_final(
-                self.page,
-                lookahead_months=route.lookahead_months,
-                start_day=start,
-                end_day=end,
-                session_is_current=lambda: self._calendar_context_matches(
-                    route, role="book", username=username),
-                log=self._log,
-            )
-        except CalendarGateError as exc:
-            raise self._calendar_failure(exc, "Book") from None
+        start, end = book_date_preferences(inputs)
+        slot = recheck_calendar_before_final(
+            self.page,
+            lookahead_months=route.lookahead_months,
+            start_day=start,
+            end_day=end,
+            session_is_current=lambda: self._calendar_context_matches(
+                route, role="book", username=username),
+            log=self._log,
+        )
         if not slot:
             return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
         self._log(f"Italy Book selected {slot.day} {slot.time_label}")