ita_reservation.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. """Read-only Prenot@Mi receipt adapter, not a final-submit read port.
  2. These objects contain observed display facts, not an inferred service/account
  3. binding or proof linking an assigned appointment time to a selected slot.
  4. Only observed Italian cancelled/confirmed states are classified; others stay UNKNOWN.
  5. No navigation, credentials, OTP, form writes or final actions live here.
  6. """
  7. from __future__ import annotations
  8. import math
  9. import re
  10. import time
  11. from dataclasses import dataclass, field
  12. from datetime import date
  13. from plugins.ita_booking_final import ReservationState
  14. from plugins.ita_calendar_query import same_origin_path
  15. from plugins.ita_protocol import MAX_PROTOCOL_ITEMS
  16. LIST_PATH = "/Reservation"
  17. DETAIL_PREFIX = "/ReservationDetail/Index/"
  18. HEADERS = ("Codice Prenotazione", "Ufficio", "Servizio", "Data", "Ora", "Stato", "Dati Richiedente")
  19. DETAIL_LABELS = ("Servizio Consolare", "Servizio Erogato", "Codice Prenotazione",
  20. "Tipo Prenotazione", "Data", "Ora", "Stato")
  21. MONTHS_IT = ("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio",
  22. "agosto", "settembre", "ottobre", "novembre", "dicembre")
  23. class ReservationReadError(ValueError):
  24. """Only adapter-owned reason codes; never include DOM text or browser errors."""
  25. def __init__(self, reason: str):
  26. self.reason = reason
  27. super().__init__(f"Italy reservation read rejected: {reason}")
  28. @dataclass(frozen=True, slots=True, repr=False)
  29. class ReservationDetail:
  30. reference: str
  31. office: str
  32. service_name: str
  33. booking_type: str
  34. day: date
  35. appointment_time: str
  36. status_text: str
  37. status_code: str
  38. state: ReservationState
  39. @dataclass(frozen=True, slots=True, repr=False)
  40. class ReservationListRow:
  41. reference: str
  42. detail_url: str
  43. office: str
  44. service_name: str
  45. day: date
  46. appointment_time: str
  47. status_text: str
  48. state: ReservationState
  49. @dataclass(frozen=True, slots=True)
  50. class ReservationListing:
  51. """Coverage of the loaded client data, NOT a fresh account-bound snapshot."""
  52. rows: tuple[ReservationListRow, ...] = field(repr=False)
  53. page_count: int
  54. waitlist_count: int = 0
  55. _CONTEXT_JS = r"""
  56. const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
  57. const fail = reason => ({error: reason});
  58. if (window.location.origin !== 'https://prenotami.esteri.it') return fail('wrong_page');
  59. if (document.readyState !== 'complete') return fail('not_ready');
  60. if (!document.querySelector('.app-menu')) return fail('authentication_missing');
  61. """
  62. DETAIL_READ_SCRIPT = _CONTEXT_JS + r"""
  63. /* coordinate:ita-reservation-detail-readonly */
  64. if (!/^\/ReservationDetail\/Index\/[^/]+$/.test(window.location.pathname)) return fail('wrong_page');
  65. const headings = Array.from(document.querySelectorAll('h4'));
  66. const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
  67. const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
  68. if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
  69. const root = booking[0].parentElement;
  70. if (!root || !root.classList.contains('my-col-6') || root.contains(applicant[0])) return fail('unsafe_scope');
  71. const nameOf = e => clean(e.textContent).match(
  72. /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:\s*$/)?.[1];
  73. const labels = Array.from(root.querySelectorAll('label')).filter(nameOf);
  74. if (labels.length !== 7 || new Set(labels.map(nameOf)).size !== 7) return fail('fields_ambiguous');
  75. const fields = {};
  76. for (const label of labels) {
  77. const row = label.parentElement;
  78. if (labels.filter(e => row.contains(e)).length !== 1) return fail('row_ambiguous');
  79. const values = [];
  80. for (const node of row.childNodes) {
  81. if (node === label || node.nodeType === 8) continue;
  82. // The observed values are text siblings or one b. Do not read nested
  83. // forms, print payloads, applicant sections or arbitrary HTML as values.
  84. if (node.nodeType !== 3 && !(node.nodeType === 1 && node.tagName === 'B' && node.children.length === 0))
  85. return fail('value_structure_changed');
  86. const value = clean(node.textContent);
  87. if (value) values.push(value);
  88. }
  89. if (values.length !== 1 || values[0].length > 256) return fail('value_ambiguous');
  90. fields[nameOf(label)] = values[0];
  91. }
  92. const codes = document.querySelectorAll('input#IDTipoStatoPrenotazione');
  93. if (codes.length !== 1 || codes[0].type !== 'hidden' || codes[0].name !== 'IDTipoStatoPrenotazione')
  94. return fail('status_control_ambiguous');
  95. return {path: window.location.pathname, fields, statusCode: clean(codes[0].value)};
  96. """
  97. LIST_READ_SCRIPT = _CONTEXT_JS + r"""
  98. /* coordinate:ita-reservation-list-readonly */
  99. if (window.location.pathname !== '/Reservation') return fail('wrong_page');
  100. const readDateCell = cell => {
  101. // Observed shape: optional hidden element(s), one non-empty text sibling.
  102. // Do not use the whole cell's textContent (includes hidden metadata), nor
  103. // innerText (unrendered DataTables pages can fall back to textContent).
  104. const nodes = Array.from(cell.childNodes), values = [];
  105. if (nodes.length > 16) return null;
  106. for (const node of nodes) {
  107. if (node.nodeType === 8) continue;
  108. if (node.nodeType === 3) {
  109. const value = clean(node.textContent);
  110. if (value) values.push(value);
  111. continue;
  112. }
  113. if (node.nodeType !== 1) return null;
  114. const style = window.getComputedStyle(node);
  115. // Own inline/hidden markers remain checkable for detached client rows.
  116. // visibility:hidden only proves a leaf hidden: descendants can override it.
  117. const hidden = node.hidden === true || node.style.display === 'none' || style.display === 'none';
  118. const hiddenLeaf = node.children.length === 0 &&
  119. (node.style.visibility === 'hidden' || style.visibility === 'hidden');
  120. if (!hidden && !hiddenLeaf) return null;
  121. // Hidden metadata is excluded structurally; never parse or log its value.
  122. }
  123. return values.length === 1 ? values[0] : null;
  124. };
  125. const $ = window.jQuery;
  126. const ids = ['dataTableReservations', 'dataTableReservationsWL'];
  127. const tables = [];
  128. for (const id of ids) {
  129. const matches = document.querySelectorAll('#' + id);
  130. if (matches.length !== 1) return fail('table_ambiguous');
  131. const table = matches[0];
  132. const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
  133. if (!$?.fn?.dataTable?.isDataTable(table)) {
  134. const empty = table.querySelectorAll('tbody tr').length === 0 && headers.length === 0 &&
  135. !table.classList.contains('dataTable') && !table.closest('.dataTables_wrapper');
  136. if (id !== ids[1] || !empty) return fail('not_ready');
  137. tables.push({id, structuralEmpty: true});
  138. continue;
  139. }
  140. // This getter is only used after isDataTable: it must never initialize a table.
  141. const api = $(table).DataTable(), pageInfo = api.page.info();
  142. const info = Object.fromEntries(['page', 'pages', 'start', 'end', 'length',
  143. 'recordsTotal', 'recordsDisplay', 'serverSide'].map(k => [k, pageInfo[k]]));
  144. const count = api.rows().count();
  145. if (!Number.isInteger(count) || count < 0 || count > 512) return fail('row_limit');
  146. if (info.serverSide !== false || api.search() || api.columns().search().toArray().some(Boolean) ||
  147. count !== info.recordsTotal || count !== info.recordsDisplay || api.rows({search: 'applied'}).count() !== count)
  148. return fail('coverage_incomplete');
  149. if (id === ids[1]) {
  150. if (count !== 0) return fail('waitlist_schema_unverified');
  151. tables.push({id, structuralEmpty: false, count, info});
  152. continue;
  153. }
  154. const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
  155. if (![7, 8].includes(headers.length) || expected.some((h, i) => headers[i] !== h) ||
  156. (headers.length === 8 && headers[7] !== '')) return fail('headers_changed');
  157. const nodes = api.rows().nodes().toArray();
  158. if (nodes.length !== count) return fail('row_nodes_incomplete');
  159. const rows = [];
  160. for (const node of nodes) {
  161. const cells = Array.from(node.children);
  162. if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
  163. const links = cells[0].querySelectorAll('a[href]');
  164. if (links.length !== 1) return fail('detail_link_ambiguous');
  165. const date = readDateCell(cells[3]);
  166. if (date === null) return fail('date_cell_structure_changed');
  167. const row = {reference: clean(cells[0].textContent), detailUrl: links[0].href,
  168. office: clean(cells[1].textContent), service: clean(cells[2].textContent),
  169. date, time: clean(cells[4].textContent), status: clean(cells[5].textContent)};
  170. if (Object.values(row).some(v => typeof v !== 'string' || !v || v.length > 256)) return fail('field_invalid');
  171. rows.push(row);
  172. // Do not access applicant cell 6 or unnamed cell 7.
  173. }
  174. tables.push({id, structuralEmpty: false, headers, count, info, rows});
  175. }
  176. return {path: window.location.pathname, tables};
  177. """
  178. DATE_DIAGNOSTIC_SCRIPT = _CONTEXT_JS + r"""
  179. /* coordinate:ita-reservation-date-diagnostic-readonly */
  180. if (window.location.pathname !== '/Reservation') return fail('wrong_page');
  181. const tables = document.querySelectorAll('#dataTableReservations');
  182. if (tables.length !== 1) return fail('table_ambiguous');
  183. const table = tables[0], $ = window.jQuery;
  184. const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
  185. const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
  186. if (![7,8].includes(headers.length) || expected.some((v,i) => headers[i] !== v) ||
  187. (headers.length === 8 && headers[7] !== '') || !$?.fn?.dataTable?.isDataTable(table))
  188. return fail('headers_changed');
  189. const nodes = $(table).DataTable().rows().nodes().toArray();
  190. if (nodes.length > 512) return fail('row_limit');
  191. const samples = [];
  192. for (const row of nodes.slice(0,3)) {
  193. const cells = Array.from(row.children);
  194. if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
  195. // Only the verified Data column. No reference, account, applicant, HTML or attributes.
  196. const cell = cells[3], children = Array.from(cell.childNodes);
  197. const text = clean(cell.textContent), rendered = clean(cell.innerText);
  198. if (text.length > 256 || rendered.length > 256) return fail('field_invalid');
  199. const parts = children.slice(0,6).map(n => {
  200. const style = n.nodeType === 1 ? window.getComputedStyle(n) : null;
  201. return {kind: n.nodeType === 3 ? 'text' : (n.nodeType === 1 &&
  202. ['SPAN','B','I','BR'].includes(n.tagName) ? n.tagName.toLowerCase() : 'other'),
  203. text: clean(n.textContent), hidden: !!style && (style.display === 'none' || style.visibility === 'hidden')};
  204. });
  205. samples.push({text, rendered, parts, partsTruncated: children.length > 6});
  206. }
  207. return {path: window.location.pathname, samples, rowsTruncated: nodes.length > 3};
  208. """
  209. def _date_shape(value: object) -> dict:
  210. """Only structural symbols and known month indexes; never emit raw field text."""
  211. if not isinstance(value, str) or len(value) > 256:
  212. raise ValueError()
  213. normalized = " ".join(value.split())
  214. shape = "".join("D" if c.isdecimal() else "L" if c.isalpha() else c if c in " /:.,-" else "?"
  215. for c in normalized[:96])
  216. months = [i for i, month in enumerate(MONTHS_IT, 1)
  217. if re.search(r"(?<![A-Za-z])" + month + r"(?![A-Za-z])", normalized, re.IGNORECASE)]
  218. try:
  219. _day(normalized)
  220. accepted = True
  221. except ReservationReadError:
  222. accepted = False
  223. return {"shape": shape, "length": len(normalized), "truncated": len(normalized) > 96,
  224. "italianMonths": months, "acceptedByCurrentParser": accepted}
  225. def read_reservation_date_diagnostic(page: object) -> dict:
  226. """One bounded extra read on a failed list parse, not an alternate parser.
  227. The raw verified date-cell strings stay local; only allowlisted shapes leave
  228. this function. A malformed diagnostic cannot leak arbitrary browser output.
  229. """
  230. try:
  231. raw = _read_current(page, DATE_DIAGNOSTIC_SCRIPT, detail=False)
  232. if (set(raw) != {"path", "samples", "rowsTruncated"} or
  233. type(raw["rowsTruncated"]) is not bool or not isinstance(raw["samples"], list) or
  234. len(raw["samples"]) > 3):
  235. raise ValueError()
  236. samples = []
  237. for item in raw["samples"]:
  238. if (not isinstance(item, dict) or set(item) != {"text", "rendered", "parts", "partsTruncated"} or
  239. type(item["partsTruncated"]) is not bool or not isinstance(item["parts"], list) or
  240. len(item["parts"]) > 6):
  241. raise ValueError()
  242. parts = []
  243. for part in item["parts"]:
  244. if (not isinstance(part, dict) or set(part) != {"kind", "text", "hidden"} or
  245. part["kind"] not in ("text", "span", "b", "i", "br", "other") or
  246. type(part["hidden"]) is not bool):
  247. raise ValueError()
  248. parts.append({"kind": part["kind"], "hidden": part["hidden"], **_date_shape(part["text"])})
  249. samples.append({"text": _date_shape(item["text"]), "rendered": _date_shape(item["rendered"]),
  250. "textEqualsRendered": item["text"] == item["rendered"],
  251. "parts": parts, "partsTruncated": item["partsTruncated"]})
  252. return {"available": True, "samples": samples, "rowsTruncated": raw["rowsTruncated"]}
  253. except Exception:
  254. return {"available": False}
  255. def _text(value: object) -> str:
  256. if (not isinstance(value, str) or not 0 < len(value) <= 256 or value != value.strip()
  257. or any(ord(c) < 32 or ord(c) == 127 for c in value)):
  258. raise ReservationReadError("field_invalid")
  259. return value
  260. def _day(value: object) -> date:
  261. value = _text(value)
  262. match = re.fullmatch(r"([0-9]{1,2}) ([A-Za-z]+) ([0-9]{4})", value)
  263. if match:
  264. try:
  265. return date(int(match[3]), MONTHS_IT.index(match[2].casefold()) + 1, int(match[1]))
  266. except ValueError:
  267. pass
  268. raise ReservationReadError("date_unrecognized") from None
  269. def _appointment_time(value: object) -> str:
  270. value = _text(value)
  271. if re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", value) is None:
  272. raise ReservationReadError("time_unrecognized")
  273. return value
  274. def _state(text: str, code: str | None = None) -> ReservationState:
  275. # A list label is a candidate; a detail must also have its observed code.
  276. # Never infer ACTIVE from "not cancelled" or from the numeric code alone.
  277. if text.casefold() == "annullata" and code in (None, "3"):
  278. return ReservationState.CANCELLED
  279. if text.casefold() == "confermata" and code in (None, "2"):
  280. return ReservationState.ACTIVE
  281. return ReservationState.UNKNOWN
  282. def _detail_path(url: object) -> str:
  283. try:
  284. path, parsed = same_origin_path(url)
  285. suffix = path.removeprefix(DETAIL_PREFIX)
  286. if (not path.startswith(DETAIL_PREFIX) or not suffix or len(suffix) > 256
  287. or any(c in suffix for c in "/\\%") or suffix in {".", ".."}
  288. or parsed.query or parsed.fragment):
  289. raise ValueError()
  290. return path
  291. except Exception:
  292. raise ReservationReadError("detail_url_invalid") from None
  293. def parse_reservation_detail(raw: object) -> ReservationDetail:
  294. if not isinstance(raw, dict) or set(raw) != {"path", "fields", "statusCode"}:
  295. raise ReservationReadError("detail_schema_changed")
  296. _detail_path("https://prenotami.esteri.it" + raw["path"] if isinstance(raw["path"], str) else None)
  297. fields = raw["fields"]
  298. if not isinstance(fields, dict) or set(fields) != set(DETAIL_LABELS):
  299. raise ReservationReadError("fields_ambiguous")
  300. values = {key: _text(value) for key, value in fields.items()}
  301. code = raw["statusCode"]
  302. if not isinstance(code, str) or not re.fullmatch(r"[0-9]{1,4}", code):
  303. raise ReservationReadError("status_code_invalid")
  304. return ReservationDetail(
  305. values["Codice Prenotazione"], values["Servizio Consolare"], values["Servizio Erogato"],
  306. values["Tipo Prenotazione"], _day(values["Data"]), _appointment_time(values["Ora"]),
  307. values["Stato"], code, _state(values["Stato"], code),
  308. )
  309. def _coverage(table: dict) -> tuple[int, int]:
  310. info, count = table.get("info"), table.get("count")
  311. if not isinstance(info, dict) or type(count) is not int or not 0 <= count <= MAX_PROTOCOL_ITEMS:
  312. raise ReservationReadError("coverage_invalid")
  313. keys = ("recordsTotal", "recordsDisplay", "page", "pages", "start", "end", "length")
  314. if any(type(info.get(k)) is not int for k in keys) or info.get("serverSide") is not False:
  315. raise ReservationReadError("coverage_invalid")
  316. total, displayed, page, pages, start, end, length = (info[k] for k in keys)
  317. if total != count or displayed != count or not 0 <= start <= end <= count:
  318. raise ReservationReadError("coverage_incomplete")
  319. expected_pages = (math.ceil(count / length) if length > 0 else 1) if count else 0
  320. if (length not in (-1,) and length <= 0) or pages != expected_pages or not 0 <= page < max(1, pages):
  321. raise ReservationReadError("pagination_invalid")
  322. if start != (page * length if length > 0 else 0) or end != (min(start + length, count) if length > 0 else count):
  323. raise ReservationReadError("pagination_invalid")
  324. return count, pages
  325. def parse_reservation_listing(raw: object) -> ReservationListing:
  326. if not isinstance(raw, dict) or set(raw) != {"path", "tables"} or raw["path"] != LIST_PATH:
  327. raise ReservationReadError("list_schema_changed")
  328. tables = raw["tables"]
  329. if not isinstance(tables, list) or len(tables) != 2 or not all(isinstance(t, dict) for t in tables):
  330. raise ReservationReadError("table_ambiguous")
  331. main, waitlist = tables
  332. if main.get("id") != "dataTableReservations" or waitlist.get("id") != "dataTableReservationsWL":
  333. raise ReservationReadError("table_ambiguous")
  334. if main.get("structuralEmpty") is not False or main.get("headers") not in (list(HEADERS), [*HEADERS, ""]):
  335. raise ReservationReadError("headers_changed")
  336. count, pages = _coverage(main)
  337. if waitlist.get("structuralEmpty") is True:
  338. if set(waitlist) != {"id", "structuralEmpty"}:
  339. raise ReservationReadError("waitlist_ambiguous")
  340. elif waitlist.get("structuralEmpty") is not False or _coverage(waitlist)[0] != 0:
  341. raise ReservationReadError("waitlist_schema_unverified")
  342. rows = main.get("rows")
  343. if not isinstance(rows, list) or len(rows) != count:
  344. raise ReservationReadError("row_nodes_incomplete")
  345. result, references, destinations = [], set(), set()
  346. for row in rows:
  347. if not isinstance(row, dict) or set(row) != {"reference", "detailUrl", "office", "service", "date", "time", "status"}:
  348. raise ReservationReadError("row_schema_changed")
  349. values = {key: _text(value) for key, value in row.items()}
  350. path = _detail_path(values["detailUrl"])
  351. if values["reference"] in references or path in destinations:
  352. raise ReservationReadError("duplicate_record")
  353. references.add(values["reference"])
  354. destinations.add(path)
  355. result.append(ReservationListRow(values["reference"], values["detailUrl"], values["office"],
  356. values["service"], _day(values["date"]), _appointment_time(values["time"]),
  357. values["status"], _state(values["status"])))
  358. return ReservationListing(tuple(result), pages)
  359. def _read_current(page: object, script: str, *, detail: bool) -> object:
  360. try:
  361. before_url, before_tab = page.url, page.tab_id
  362. path, parsed = same_origin_path(before_url)
  363. if parsed.query or parsed.fragment or (not detail and path != LIST_PATH):
  364. raise ReservationReadError("wrong_page")
  365. if detail:
  366. _detail_path(before_url)
  367. if not isinstance(before_tab, str) or not before_tab:
  368. raise ReservationReadError("context_changed")
  369. raw = page.run_js(script)
  370. if page.url != before_url or page.tab_id != before_tab:
  371. raise ReservationReadError("context_changed")
  372. if not isinstance(raw, dict) or raw.get("path") != path:
  373. reason = "not_ready" if isinstance(raw, dict) and raw == {"error": "not_ready"} else "page_read_rejected"
  374. raise ReservationReadError(reason)
  375. return raw
  376. except ReservationReadError:
  377. raise
  378. except Exception:
  379. raise ReservationReadError("browser_read_failed") from None
  380. def read_reservation_detail(page: object) -> ReservationDetail:
  381. """Read the current detail page once. No URL, reference or PII is logged."""
  382. return parse_reservation_detail(_read_current(page, DETAIL_READ_SCRIPT, detail=True))
  383. def read_reservation_listing(page: object, *, timeout: float = 5, poll_interval: float = 0.25) -> ReservationListing:
  384. """Two stable reads within a bound, reusing the existing count tool pattern.
  385. Only not-ready states are polled; unsupported schemas/coverage fail closed.
  386. This checks the current page and never navigates, draws or clears filters.
  387. """
  388. if (any(type(v) not in (int, float) or not math.isfinite(v) or v <= 0 for v in (timeout, poll_interval))
  389. or poll_interval > timeout or timeout > 60):
  390. raise ReservationReadError("wait_config_invalid")
  391. try:
  392. binding = (page.url, page.tab_id)
  393. except Exception:
  394. raise ReservationReadError("browser_read_failed") from None
  395. deadline, previous = time.monotonic() + timeout, None
  396. while time.monotonic() < deadline:
  397. try:
  398. try:
  399. context_matches = (page.url, page.tab_id) == binding
  400. except Exception:
  401. raise ReservationReadError("browser_read_failed") from None
  402. if not context_matches:
  403. raise ReservationReadError("context_changed")
  404. current = parse_reservation_listing(_read_current(page, LIST_READ_SCRIPT, detail=False))
  405. except ReservationReadError as error:
  406. if error.reason != "not_ready":
  407. raise
  408. previous = None
  409. else:
  410. if current == previous:
  411. return current
  412. previous = current
  413. time.sleep(min(poll_interval, max(0, deadline - time.monotonic())))
  414. raise ReservationReadError("stability_timeout")