| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635 |
- """Finite live acceptance wiring, not a second scheduler.
- Execute existing GCO spawn/monitor/trigger/stop methods. Only order API and
- telemetry are substituted; pool allocation and Italy OTP keep their SDK.
- Redis is an owned, non-persistent Unix-socket subprocess (never shared Redis).
- This module is loaded only by explicit --local-preflight / --local-run.
- """
- from __future__ import annotations
- from contextlib import ExitStack, contextmanager
- import copy
- import hashlib
- import json
- import os
- from pathlib import Path
- import shutil
- import socket
- import subprocess
- import tempfile
- import threading
- import time
- from types import SimpleNamespace
- from unittest.mock import patch
- from uuid import uuid4
- import redis
- import configure
- from booker import OrderBookerGCO
- from sentinel import SentinelGCO
- from plugins.ita_calendar_book import book_date_preferences, read_calendar_service, verify_precommit_selection
- from plugins.ita_calendar_session import CalendarRequestAudit
- from plugins.ita_otp import validate_cloud_otp_environment, validate_cloud_otp_logging
- from plugins.ita_plugin import (
- BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
- PERSISTENT_BROWSER_PROFILE_KEY,
- )
- from plugins.ita_protocol import ItaCapability, resolve_route_config
- from plugins.ita_booking_final import FinalBookingError, FinalOutcomeUnknown
- from plugins import ita_workflow
- from tools.ita_final_evidence import claim_once, require_unused_claim
- from tools.ita_local_handoff import ITA_LOCAL_HANDOFF_ROOT
- from toolkit.vs_cloud_api import VSCloudApi
- from tools.debug_ita_session import _get_credentials, resolve_chrome_path
- from tools.plugin_tester import PluginTester
- from utils.local_account import load_local_account
- from vs_types import AvailabilityStatus, GroupConfig, VSAccount
- CONTRACT = "existing-framework-local-prefinal-v1"
- FINAL_CONTRACT = "existing-framework-local-auto-submit-once-v4"
- ROOT = Path(__file__).resolve().parents[1]
- class LocalAcceptanceError(RuntimeError):
- """Only static diagnostic codes, never credentials or upstream bodies."""
- def emit(event, **fields):
- print("ITA_QUERY_BOOK_" + event + "=" + json.dumps(fields, sort_keys=True), flush=True)
- def load_settings(args):
- validate_cloud_otp_logging()
- if configure.TEST_ACCOUNT:
- raise LocalAcceptanceError("test_account_override_enabled")
- path = Path(args.config)
- groups = json.loads((path if path.is_absolute() else ROOT / path).read_text())
- matches = [g for g in groups if g.get("identifier") == args.group]
- if len(matches) != 1:
- raise LocalAcceptanceError("group_missing_or_ambiguous")
- source = GroupConfig.from_json(matches[0])
- if (source.plugin_config.plugin_name != "ita_plugin" or len(source.appointment_types) != 1
- or not source.sentinel.account_pool_id or source.sentinel.signal_ttl <= 0
- or source.free_config.get("query_mode") != "calendar"
- or source.free_config.get("otp_mode") != "cloud"
- or source.free_config.get("final_submit_enabled") is not False):
- raise LocalAcceptanceError("requires_single_calendar_query_group_with_cloud_otp_and_final_disabled")
- apt = source.appointment_types[0]
- route = resolve_route_config(source.free_config.get("apt_configs", {}), apt.routing_key)
- if (route.capability != ItaCapability.SINGLE_SCHENGEN_TOURISM
- or route.mail is None or route.mail.authorization_source != "account"):
- raise LocalAcceptanceError("requires_single_tourism_route_and_account_mailbox")
- preferences = {key: value for key, value in (
- ("expected_start_date", args.expected_start_date), ("expected_end_date", args.expected_end_date)) if value}
- book_date_preferences(preferences)
- proxy = PluginTester.parse_proxy_url(args.proxy)
- if proxy.ip not in {"127.0.0.1", "localhost", "::1"} or not 1 <= proxy.port <= 65535:
- raise LocalAcceptanceError("requires_explicit_loopback_proxy")
- return source, route, proxy, preferences
- def build_groups(source, run_id, *, submit_once=False):
- """Copy existing config; do not publish or edit production groups."""
- query = source.model_copy(deep=True)
- query.identifier = "ita-local-query-" + run_id
- query.enable, query.debug, query.need_account, query.need_proxy = True, False, True, True
- query.sentinel.target_instances = 1
- query.proxy_pool = ["local-test-proxy"]
- query.free_config.pop(PERSISTENT_BROWSER_PROFILE_KEY, None)
- query.appointment_types[0].weight = max(1, query.appointment_types[0].weight)
- book = query.model_copy(deep=True)
- book.identifier = "ita-local-book-" + run_id
- book.booker.account_source = "order"
- book.booker.target_instances = 1
- book.free_config.update(query_mode="services_probe", otp_mode="cloud", final_submit_enabled=submit_once)
- return query, book
- class LocalFinalSubmission:
- """Single-dispatch fence around the EXISTING production final workflow.
- No new receipt matcher, POST implementation or retry policy. Reuse the
- exclusive/fsynced claim helper, scoped to site + applicant + service (not
- run id, date or routing alias). A restart cannot silently submit again.
- Legacy final-evidence-once.claim is never read, removed or reset here;
- the production receipt baseline still rejects existing active/unknown rows.
- """
- def __init__(self, applicant, route, *, root=ITA_LOCAL_HANDOFF_ROOT):
- self.username = applicant.username.strip().casefold()
- self.route = route
- identity = json.dumps(["prenotami.esteri.it", self.username, str(route.service_id)])
- self.claim_path = Path(root) / "query-book-final" / (hashlib.sha256(identity.encode()).hexdigest() + ".claim")
- self.used = self.possibly_submitted = False
- self.selection = {}
- self.failure_reason = None
- require_unused_claim(self.claim_path) # Before browser/pool allocation.
- def submit(self, plugin, route, observed, production_submit):
- if (self.used or route != self.route or observed.get("book") is None
- or observed["book"].plugin is not plugin
- or plugin.config.account.username.strip().casefold() != self.username):
- raise LocalAcceptanceError("final_applicant_or_route_changed")
- self.used = True
- require_unused_claim(self.claim_path)
- approval = plugin.last_booking_precommit
- verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page), approval=approval)
- slot = approval.candidate
- self.selection = {"selectionVerified": True, "selectedDate": slot.day.isoformat(), "selectedTime": slot.time_label}
- emit("FINAL_TARGET", **self.selection, routingKey=route.routing_key, serviceId=route.service_id,
- remaining=slot.slots_free, createsRealAppointment=True, automaticSubmission=True)
- # Only wrap native dispatch. The production core FIRST reads a fresh
- # receipt baseline and rejects active/waitlist/unknown history.
- native_factory = ita_workflow.NativeFinalSubmitter
- owner = self
- class FencedNative:
- def __init__(self, page, target, current):
- if (page is not plugin.page or target.applicant != owner.username
- or target.service_id != str(route.service_id) or target.approval is not approval):
- raise LocalAcceptanceError("final_target_changed")
- self.native = native_factory(page, target, current)
- def __getattr__(self, name):
- return getattr(self.native, name)
- def __call__(self):
- if owner.possibly_submitted or plugin.last_booking_precommit is not approval:
- raise LocalAcceptanceError("final_already_attempted_do_not_rerun")
- for item in observed.values():
- if item.audit.settled_snapshot()["finalRequests"] != 0:
- raise LocalAcceptanceError("unexpected_final_request_do_not_rerun")
- verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page), approval=approval)
- claim_once(owner.claim_path)
- owner.possibly_submitted = True
- emit("FINAL_DISPATCH", automaticRetry=False, possiblySubmitted=True)
- return self.native()
- with patch.object(ita_workflow, "NativeFinalSubmitter", FencedNative):
- try:
- # This observer already owns the page's passive callback.
- # Lend it to production final; keep coverage through cleanup.
- return production_submit(plugin, route, request_audit=observed["book"].audit)
- except FinalBookingError:
- self.failure_reason = "receipt_baseline_or_final_context_rejected"
- raise
- def check_dependencies(proxy):
- executable = shutil.which("redis-server")
- if not executable:
- raise LocalAcceptanceError("redis_server_missing_run_brew_install_redis")
- chrome = resolve_chrome_path(os.environ)
- with socket.create_connection((proxy.ip, proxy.port), timeout=3):
- pass # Check before allocating a pool account. Not an internet test.
- return executable, chrome
- @contextmanager
- def private_redis(executable):
- # /tmp keeps the Unix socket below macOS's path-length limit. Only this
- # owned directory/process is removed; no FLUSHDB, shared service or port.
- with tempfile.TemporaryDirectory(prefix="ita-qb-", dir="/tmp") as directory:
- unix_socket = str(Path(directory) / "redis.sock")
- process = subprocess.Popen([
- executable, "--port", "0", "--unixsocket", unix_socket,
- "--unixsocketperm", "700", "--save", "", "--appendonly", "no",
- "--dir", directory, "--daemonize", "no",
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- config = {"unix_socket_path": unix_socket, "db": 0, "decode_responses": True,
- "socket_timeout": 2, "socket_connect_timeout": 2}
- client = redis.Redis(**config)
- try:
- deadline = time.monotonic() + 8
- while True:
- if process.poll() is not None:
- raise LocalAcceptanceError("private_redis_exited")
- try:
- if client.ping():
- break
- except redis.exceptions.RedisError:
- pass
- if time.monotonic() >= deadline:
- raise LocalAcceptanceError("private_redis_not_ready")
- time.sleep(0.1)
- yield config
- finally:
- try:
- client.close()
- finally:
- if process.poll() is None:
- process.terminate()
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait(timeout=5)
- class LocalCloudBoundary:
- """Only cloud order/telemetry are local. Pool selection is never reimplemented."""
- def __init__(self, api, group, route, proxy, applicant, preferences):
- self.api, self.group, self.route, self.proxy = api, group, route, proxy
- self.applicant = applicant
- self.order = {"id": -1, "order_id": "LOCAL-ACCEPTANCE", "status": "processing",
- "user_inputs": {**preferences, "username": applicant.username, "password": applicant.password}}
- self.pool_calls = self.order_calls = self.forbidden_calls = 0
- self.query_account = None
- self.error = None
- def get_next_account(self, pool_name, account_cd):
- self.pool_calls += 1
- if self.pool_calls != 1 or (pool_name, account_cd) != (
- self.group.sentinel.account_pool_id, self.group.sentinel.account_cd):
- raise LocalAcceptanceError("unexpected_pool_allocation")
- try:
- raw = self.api.get_next_account(pool_name, account_cd)
- if not isinstance(raw, dict) or raw.get("pool_name") != pool_name or raw.get("status") != "active":
- raise LocalAcceptanceError("pool_account_invalid")
- account = VSAccount.model_validate(raw)
- if not account.password:
- raise LocalAcceptanceError("pool_website_password_missing")
- validate_cloud_otp_environment(self.route.mail, account.username)
- if account.username.strip().casefold() == self.applicant.username.strip().casefold():
- raise LocalAcceptanceError("query_and_book_accounts_same_choose_other_applicant")
- self.query_account = account
- emit("POOL", accountId=account.id, pool=pool_name, accountsDistinct=True)
- return raw
- except Exception as exc:
- self.error = str(exc) if isinstance(exc, LocalAcceptanceError) else "pool_allocation_failed"
- raise LocalAcceptanceError(self.error) from None
- def get_next_proxy(self, *_args):
- return self.proxy.model_dump()
- def get_vas_task_pop(self, queue_name):
- self.order_calls += 1
- if queue_name != "auto." + self.route.routing_key or self.order_calls != 1:
- raise LocalAcceptanceError("unexpected_local_order_request")
- return copy.deepcopy(self.order)
- def slot_refresh_start(self, *_args, **_kwargs):
- pass
- def slot_refresh_success(self, *_args, **_kwargs):
- pass
- def slot_refresh_fail(self, *_args, **_kwargs):
- self.error = self.error or "query_failed"
- def slot_snapshot_report(self, *_args, **_kwargs):
- pass
- def __getattr__(self, name):
- # Reject cloud updates/notifications and any new dependency rather
- # than silently forwarding a synthetic order id to the backend.
- self.forbidden_calls += 1
- raise LocalAcceptanceError("unexpected_cloud_operation")
- class ObservedPlugin:
- """A test observer around a real factory-created plugin, not an algorithm."""
- def __init__(self, plugin, role):
- self.plugin, self.role = plugin, role
- self.audit = None
- self.calls = 0
- self.result = None
- self.error = None
- self.cleanup_ok = False
- self.last_counts = None
- def __getattr__(self, name):
- return getattr(self.plugin, name)
- def create_session(self):
- try:
- self.plugin.create_session()
- self.audit = CalendarRequestAudit(self.plugin.page, include_time_slots=True)
- self.audit.start()
- except Exception as exc:
- self.error = type(exc).__name__
- raise LocalAcceptanceError(self.role + "_session_failed") from None
- def query(self, apt):
- return self._call("query", apt)
- def book(self, slot_info, user_inputs):
- return self._call("book", slot_info, user_inputs)
- def _call(self, operation, *args):
- self.calls += 1
- if operation != self.role or self.calls != 1:
- raise LocalAcceptanceError("unexpected_plugin_invocation")
- try:
- self.result = getattr(self.plugin, operation)(*args)
- return self.result
- except Exception as exc:
- self.error = type(exc).__name__
- if isinstance(exc, FinalOutcomeUnknown):
- raise # Preserve the native Booker's pause-on-unknown branch.
- raise LocalAcceptanceError(self.role + "_operation_failed") from None
- def cleanup(self):
- # The GCO may remove a failed instance before the final audit. Keep
- # that failure visible; never turn retained counters into live proof.
- try:
- if self.audit is not None:
- try:
- self.last_counts = self.audit.settled_snapshot()
- finally:
- self.audit.stop()
- finally:
- self.plugin.cleanup()
- self.cleanup_ok = True
- def observe_factory(gco, role, stack, observed):
- factory_create = gco.m_factory.create
- cfg = gco.m_cfg.plugin_config
- gco.m_factory.register_plugin(cfg.plugin_name, str(ROOT / "plugins/ita_plugin.py"), "ItaPlugin")
- def create(*args):
- instance = ObservedPlugin(factory_create(*args), role)
- observed[role] = instance
- return instance
- stack.enter_context(patch.object(gco.m_factory, "create", side_effect=create))
- def framework_log(message):
- # GCO errors can include arbitrary provider exception strings. Keep only
- # lifecycle markers here; plugin observers produce safe failure codes.
- for marker in ("Triggering BOOK", "SLOT FOUND", "spawned", "Stopping", "Cleaned up",
- "Entering username", "Entering password", "Login form submitted",
- "Successfully reached authenticated /UserArea", "OTP sent",
- "automatic OTP DOM write verified", "Calendar found the first positive month"):
- if marker in message:
- emit("FRAMEWORK", marker=marker)
- break
- def run_framework_once(query_group, book_group, route, cloud, redis_config, *, final_control=None):
- observed, threads = {}, []
- report = {"contract": FINAL_CONTRACT if final_control else CONTRACT, "passed": False, "outcome": "failed",
- "cloudOrders": False, "finalSubmissionEnabled": final_control is not None, "liveAcceptance": True,
- "queryCalls": 0, "bookCalls": 0, "signalPublished": False,
- "signalReadByBooker": False, "selectionVerified": False, "cleanupVerified": False}
- gc_objects = []
- local_success_reports = []
- if final_control:
- report.update(bookingConfirmed=False, bookResultSuccess=False, automaticRetry=False)
- with ExitStack() as stack:
- def forbidden_cloud_write(*_args, **_kwargs):
- cloud.forbidden_calls += 1
- raise LocalAcceptanceError("unexpected_cloud_operation")
- boundary = SimpleNamespace(Instance=lambda: cloud, lock_account=forbidden_cloud_write)
- # Existing tests use these same dependency seams. Do not patch GCO
- # implementation methods, signal serialization, filtering or TTL.
- for cls in (SentinelGCO, OrderBookerGCO):
- stack.enter_context(patch.dict(cls.__init__.__globals__, {"VSCloudApi": boundary}))
- production_submit = ita_workflow.submit_final
- stack.enter_context(patch.object(ita_workflow, "submit_final", side_effect=(
- lambda plugin, actual_route: final_control.submit(plugin, actual_route, observed, production_submit)
- ) if final_control else LocalAcceptanceError("final_submission_forbidden")))
- sentinel = SentinelGCO(query_group, redis_config, framework_log)
- booker = OrderBookerGCO(book_group, redis_config, framework_log)
- # Block reporting BEFORE the shared asynchronous executor can enqueue
- # anything. Its callback could otherwise outlive this patch scope.
- def capture_success(task_id, order_id, result):
- if (final_control is None or task_id != -1 or order_id != cloud.order["order_id"]
- or result is not observed["book"].result or result.success is not True
- or local_success_reports):
- return forbidden_cloud_write()
- local_success_reports.append(result) # Standard callback; no cloud enqueue.
- stack.enter_context(patch.object(booker, "_push_success_notification", side_effect=capture_success))
- if final_control:
- def local_pause(task_id, data):
- if str(task_id) != "-1" or data != {"status": "pause"}:
- return forbidden_cloud_write()
- cloud.order["status"] = "pause"
- # Restore only this test seam, not the counters/state accumulated
- # during the run (patch.dict(__dict__) would restore those too).
- cloud.update_vas_task = local_pause
- stack.callback(cloud.__dict__.pop, "update_vas_task", None)
- gc_objects.extend((sentinel, booker))
- observe_factory(sentinel, "query", stack, observed)
- observe_factory(booker, "book", stack, observed)
- signal_key = sentinel._get_redis_key(route.routing_key)
- published_digest = None
- original_setex, original_get = sentinel.redis_client.setex, booker.redis_client.get
- def publish(key, ttl, payload):
- nonlocal published_digest
- ok = original_setex(key, ttl, payload)
- if key == signal_key and ok:
- published_digest = hashlib.sha256(payload.encode()).hexdigest()
- report["signalPublished"] = True
- emit("SIGNAL", published=True, ttl=ttl)
- return ok
- def read(key):
- payload = original_get(key)
- if key == signal_key and payload and published_digest:
- data = payload.encode() if isinstance(payload, str) else payload
- report["signalReadByBooker"] = hashlib.sha256(data).hexdigest() == published_digest
- return payload
- stack.enter_context(patch.object(sentinel.redis_client, "setex", side_effect=publish))
- stack.enter_context(patch.object(booker.redis_client, "get", side_effect=read))
- thread_class = threading.Thread
- def tracked_thread(*args, **kwargs):
- # Original trigger still starts and joins its own thread. Track
- # ownership for Ctrl+C cleanup; don't create a second job runner.
- finished = threading.Event()
- target = kwargs.pop("target")
- def observed_target(*target_args, **target_kwargs):
- try:
- return target(*target_args, **target_kwargs)
- finally:
- finished.set()
- thread = thread_class(*args, target=observed_target, **kwargs, daemon=True)
- threads.append((thread, finished))
- return thread
- stack.enter_context(patch.dict(booker._booking_trigger_loop.__globals__, {
- "threading": SimpleNamespace(Thread=tracked_thread, RLock=threading.RLock, Event=threading.Event)}))
- try:
- emit("STAGE", stage="applicant_login", orderSource="local_only")
- booker._spawn_worker(route.routing_key)
- if len(booker.m_tasks) != 1:
- raise LocalAcceptanceError("applicant_session_not_created")
- emit("STAGE", stage="pool_login")
- sentinel._spawn_sentinel_worker()
- if len(sentinel.m_tasks) != 1:
- raise LocalAcceptanceError(cloud.error or "query_session_not_created")
- if observed["query"].page is observed["book"].page:
- raise LocalAcceptanceError("browser_sessions_not_separate")
- emit("STAGE", stage="query_and_publish")
- # Exactly one iteration of the existing loops, as in the offline
- # fixture. No independent queue, TTL, retry or polling algorithm.
- with patch.object(sentinel.m_stop_event, "is_set", side_effect=[False, True]):
- sentinel._monitor_loop()
- query = observed["query"]
- if query.error or query.result is None or cloud.error:
- raise LocalAcceptanceError("query_did_not_complete")
- if query.result.success and (query.result.availability_status != AvailabilityStatus.Available
- or query.result.earliest_date is None):
- raise LocalAcceptanceError("query_did_not_return_date_availability")
- report["earliestDate"] = query.result.earliest_date.strftime("%Y-%m-%d") if query.result.earliest_date else None
- if not query.result.success:
- if query.result.availability_status != AvailabilityStatus.NoneAvailable:
- raise LocalAcceptanceError("unexpected_query_result")
- report["outcome"] = "no_availability"
- elif not report["signalPublished"]:
- raise LocalAcceptanceError("redis_publication_failed")
- else:
- emit("STAGE", stage="booker_receive_and_select")
- with patch.object(booker.m_stop_event, "is_set", side_effect=[False, True]):
- booker._booking_trigger_loop()
- book = observed["book"]
- if book.error:
- raise LocalAcceptanceError("book_failed")
- if book.calls == 0:
- report["outcome"] = "not_triggered_expired_or_date_filtered"
- elif (book.result is not None and book.result.success is False
- and book.result.label == BOOKING_CALENDAR_PREFINAL_STOP_LABEL):
- approval = book.last_booking_precommit
- verify_precommit_selection(book.page, runtime_service=read_calendar_service(book.page), approval=approval)
- report.update(selectionVerified=True, selectedDate=approval.candidate.day.isoformat(),
- selectedTime=approval.candidate.time_label, outcome="pre_final")
- elif book.result is not None and book.result.success:
- if final_control is None:
- raise LocalAcceptanceError("unexpected_book_success_before_final")
- attempt = getattr(book.plugin, "_production_final_attempt", None)
- if (not final_control.possibly_submitted or attempt is None or attempt.state != "confirmed"
- or book.plugin._production_book_result is not book.result
- or len(local_success_reports) != 1):
- raise LocalAcceptanceError("final_success_not_verified")
- report.update(**final_control.selection, outcome="confirmed", bookingConfirmed=True,
- bookResultSuccess=True, confirmedDate=book.result.book_date,
- confirmedTime=book.result.book_time, successHandledLocally=True)
- elif (book.result is not None and book.result.success is False
- and book.result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL):
- report["outcome"] = "book_no_selection"
- elif final_control and final_control.possibly_submitted and book.result is not None and book.result.success is False:
- report["outcome"] = "rejected_do_not_retry"
- else:
- raise LocalAcceptanceError("unexpected_book_result")
- for role, item in observed.items():
- # The owner snapshots before stopping its audit. Browser
- # teardown may then fail; that does not invalidate these
- # connected counters or justify reading a stopped audit.
- counts = item.last_counts if item.last_counts is not None else item.audit.settled_snapshot()
- report[role + "Requests"] = counts
- expected_final = 1 if role == "book" and final_control and final_control.possibly_submitted else 0
- if counts["finalRequests"] != expected_final:
- raise LocalAcceptanceError("unexpected_final_request_do_not_rerun")
- if counts["otpRequests"] > 1 or counts["avantiPosts"] > 1:
- raise LocalAcceptanceError("unexpected_repeated_preparation")
- if cloud.forbidden_calls:
- raise LocalAcceptanceError("unexpected_cloud_operation")
- report["passed"] = (report["outcome"] == ("confirmed" if final_control else "pre_final") and report["signalPublished"]
- and report["signalReadByBooker"] and cloud.pool_calls == cloud.order_calls == 1)
- except KeyboardInterrupt:
- report.update(outcome="interrupted", passed=False)
- except Exception as exc:
- report.update(passed=False, outcome="failed", errorType=type(exc).__name__,
- reason=str(exc) if isinstance(exc, LocalAcceptanceError) else "local_acceptance_failed")
- finally:
- for role, item in observed.items():
- report[role + "Calls"] = item.calls
- if item.error:
- report[role + "ErrorType"] = item.error
- # Stop real GCOs and their owned pages before disposing Redis.
- for gco in gc_objects:
- gco.stop()
- for item in observed.values():
- if not item.cleanup_ok:
- try:
- item.cleanup()
- except Exception:
- report["passed"] = False
- for thread, finished in threads:
- if thread.ident is not None:
- # Keep cloud/final guards installed until the original
- # callback really exits, even if Ctrl+C interrupted join.
- # Outstanding SDK I/O follows its existing timeout.
- if not finished.is_set():
- emit("STAGE", stage="waiting_for_inflight_call_cleanup_no_retry")
- while not finished.is_set():
- try:
- finished.wait(timeout=0.5)
- except KeyboardInterrupt:
- report["passed"] = False
- thread.join(timeout=1)
- report["cleanupVerified"] = (all(item.cleanup_ok for item in observed.values())
- and not any(thread.is_alive() for thread, _ in threads))
- report["passed"] = report["passed"] and report["cleanupVerified"]
- if final_control:
- # Preserve confirmed business outcome even if cleanup failed;
- # never suggest a new booking to repair a diagnostic failure.
- report.update(final_control.selection)
- report.update(possiblySubmitted=final_control.possibly_submitted, automaticRetry=False)
- if final_control.failure_reason:
- report["finalReason"] = final_control.failure_reason
- if final_control.possibly_submitted and report["outcome"] not in {"confirmed", "rejected_do_not_retry"}:
- report.update(outcome="unknown_do_not_retry", passed=False)
- for role, item in observed.items():
- if item.last_counts is not None:
- report[role + "Requests"] = item.last_counts
- for gco in gc_objects:
- gco.redis_client._client.close()
- return report
- def main_local(args):
- stage = "preflight"
- try:
- group, route, proxy, preferences = load_settings(args)
- submit_once = getattr(args, "submit_once", False)
- if submit_once and not getattr(args, "local_run", False):
- raise LocalAcceptanceError("real_submission_requires_local_run")
- executable, chrome = check_dependencies(proxy)
- emit("PREFLIGHT", contract=FINAL_CONTRACT if submit_once else CONTRACT, ready=True, pool=group.sentinel.account_pool_id,
- routingKey=route.routing_key, cloudOrders=False, finalSubmissionEnabled=submit_once)
- if args.local_preflight:
- return 0
- stage = "applicant_credentials"
- if args.book_account_file:
- applicant = load_local_account(args.book_account_file)
- else:
- print("Book applicant account (not the Query pool account); OTP mailbox must already be authorized.", flush=True)
- username, password = _get_credentials({"ITA_USERNAME": os.environ.get("ITA_BOOK_USERNAME", ""),
- "ITA_PASSWORD": os.environ.get("ITA_BOOK_PASSWORD", "")}, non_interactive=False)
- applicant = VSAccount(username=username, password=password)
- if not applicant.password:
- raise LocalAcceptanceError("applicant_website_password_missing")
- validate_cloud_otp_environment(route.mail, applicant.username)
- final_control = LocalFinalSubmission(applicant, route) if submit_once else None
- groups = build_groups(group, uuid4().hex[:10], submit_once=submit_once)
- cloud = LocalCloudBoundary(VSCloudApi.Instance(), group, route, proxy, applicant, preferences)
- stage = "local_redis_and_framework"
- with private_redis(executable) as redis_config, patch.dict(os.environ, {"CHROME_BIN": str(chrome)}):
- report = run_framework_once(*groups, route, cloud, redis_config, final_control=final_control)
- emit("LOCAL_RESULT", **report)
- if report.get("possiblySubmitted") and not report["passed"]:
- return 4 # Receipt review, NEVER rerun to diagnose a possible write.
- return 0 if report["passed"] else (2 if report["outcome"] in {
- "no_availability", "book_no_selection", "not_triggered_expired_or_date_filtered"} else 1)
- except KeyboardInterrupt:
- emit("LOCAL_FAILED", stage=stage, reason="interrupted")
- return 130
- except Exception as exc:
- emit("LOCAL_FAILED", stage=stage, errorType=type(exc).__name__,
- reason=str(exc) if isinstance(exc, LocalAcceptanceError) else "check_local_configuration_or_dependency")
- return 1
|