返回 last30days-skill
x_api.py
根目录 / skills / last30days / scripts / lib / x_api.py
1 """Direct X API v2 backend (``xapi``) and the shared v2 response parser.
2
3 ``xapi`` searches X through ``api.x.com/2`` with an app-only bearer token
4 (``X_BEARER_TOKEN``). Full-archive search is tried first; when the developer
5 project is not enrolled for it (HTTP 403 with an enrollment marker), the
6 search retries once against recent search with the window clamped to the
7 last seven days and the truncation named in the result.
8
9 This module also owns the one X API v2 parser (``parse_v2_response``) that
10 ``xurl_x`` delegates to, plus the snowflake, handle-grammar, and
11 generated-sequence helpers that ``grok_x`` imports back.
12
13 Security contract: the bearer travels only in the Authorization
14 header; every failure becomes an engine-authored fixed string chosen by
15 status code plus a marker match on the body, and the response body, reason
16 phrase, and headers never enter an error string, a log line, or an
17 exception. Topic and handle text is sanitized before it enters a query, and
18 the research window is always carried by request parameters.
19 """
20
21 from __future__ import annotations
22
23 import re
24 import time
25 from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
26 from datetime import datetime, timedelta, timezone
27 from typing import Any, Callable, Dict, List, Optional
28
29 from . import health, http, log
30 from .relevance import token_overlap_relevance as _compute_relevance
31
32 _API_BASE = "https://api.x.com/2"
33 _SEARCH_ALL_URL = f"{_API_BASE}/tweets/search/all"
34 _SEARCH_RECENT_URL = f"{_API_BASE}/tweets/search/recent"
35
36 # Depth configurations: number of posts to collect per query (shared with
37 # xurl_x, which re-imports this table). The API minimum per page is 10.
38 DEPTH_CONFIG = {
39 "quick": 10,
40 "default": 30,
41 "deep": 60,
42 }
43
44 # X API v2 caps a search query at 512 characters (Basic) and pages at 10..100.
45 MAX_QUERY_CHARS = 512
46 MIN_PAGE_RESULTS = 10
47 MAX_PAGE_RESULTS = 100
48 # Recent search reaches back seven days; end_time must be at least ten
49 # seconds before now, so a "today" window keeps a small safety margin.
50 RECENT_WINDOW_DAYS = 7
51 END_TIME_SAFETY_SECONDS = 30
52 TIMEOUT_SECONDS = 30
53 RETRIES = 2
54 # Wall-clock budget for one search (all pages, including the recent-search
55 # fallback). A throttled or slow walk returns what it has instead of holding
56 # the whole run; the source's per-request timeout still bounds each page.
57 DEADLINE_SECONDS = 90
58 # One budget shared by every supplemental handle lane of a run (explicit
59 # from, extracted from, about, related), started once by the caller: the
60 # point is to bound the total, not each part.
61 LANE_BUDGET_SECONDS = 150.0
62
63 TRUNCATION_DETAIL = "window truncated to 7 days"
64 # Receipt when the lane budget stopped a search before ``count`` posts were
65 # collected: the posts kept are real, the coverage is not complete.
66 DEADLINE_DETAIL = "search stopped at the lane deadline; results may be incomplete"
67
68 # The one description of what an app-only bearer can reach. Doctor and the
69 # prescriptions quote it; the bearer path is never described as parity with
70 # the connector lane.
71 BEARER_COVERAGE_NOTE = (
72 "recent posts, about the last week, unless your X developer project has "
73 "full-archive access"
74 )
75
76 # Engine-authored fixed error strings. Each carries a marker that
77 # http.classify_failure recognizes, because the X retrieval branch classifies
78 # by message text only.
79 ERR_PAYMENT_REQUIRED = "xapi: payment required (X API credits exhausted)"
80 ERR_UNAUTHORIZED = "xapi: unauthorized (bearer token rejected)"
81 ERR_FORBIDDEN = "xapi: forbidden (bearer token lacks access)"
82 ERR_RATE_LIMITED = "xapi: rate limit exceeded (X API)"
83 ERR_TIMED_OUT = "xapi: timed out"
84 ERR_UNREACHABLE = "xapi: connection error (X API unreachable)"
85 ERR_NO_TOKEN = "No X_BEARER_TOKEN configured"
86 ERR_EMPTY_QUERY = "xapi: empty query after sanitizing"
87
88 # Failures that end every remaining lane for the run (the key itself is the
89 # problem, not this request).
90 _FATAL_ERRORS = frozenset({ERR_PAYMENT_REQUIRED, ERR_UNAUTHORIZED, ERR_FORBIDDEN})
91
92 # A 403 whose body carries one of these is "this project is not enrolled for
93 # full-archive search", which recent search can still serve.
94 _ENROLLMENT_MARKERS = (
95 "client-not-enrolled",
96 "not enrolled",
97 "enrolled",
98 "access level",
99 "subset of",
100 )
101 # X-specific body markers for credit exhaustion, matched on any status on
102 # top of http.classify_failure's shared payment-required markers: X reports
103 # a depleted pay-per-use balance under more than one code and title.
104 _X_CREDIT_MARKERS = ("creditsdepleted", "credits depleted")
105
106 # Twitter/X snowflake epoch (2010-11-04T01:42:54.657Z) in milliseconds.
107 _SNOWFLAKE_EPOCH_MS = 1288834974657
108
109 # X's real handle grammar. Handles are interpolated into post URLs and into
110 # search operators (from:, @), so anything outside this charset is rejected
111 # rather than passed through. entity_extract applies the same rule to
112 # @mentions.
113 _HANDLE_RE = re.compile(r"[A-Za-z0-9_]{1,15}")
114
115 # Grouping syntax that carries no lexical meaning in a topic, mirroring
116 # bird_x. Double quotes are handled separately: xapi strips them all and
117 # wraps the core in exactly one phrase pair, so a planner quote can never
118 # close the phrase early.
119 _GROUPING_CHARS = "“”()[]{}"
120 _QUOTE_CHARS = "\"„‟"
121 _APOSTROPHES = "'‘’"
122
123
124 def _log(msg: str) -> None:
125 log.source_log("xapi", msg, tty_only=False)
126
127
128 def _utcnow() -> datetime:
129 """Current UTC time; a seam tests patch to pin the window arithmetic."""
130 return datetime.now(timezone.utc)
131
132
133 # ---------------------------------------------------------------------------
134 # Shared helpers (moved here from grok_x; grok_x imports them back)
135 # ---------------------------------------------------------------------------
136
137
138 def _decode_snowflake(post_id: str) -> Optional[datetime]:
139 """Recover a post's creation time from its id, with no network call."""
140 try:
141 value = int(str(post_id).strip())
142 except (TypeError, ValueError):
143 return None
144 if value <= 0:
145 return None
146 try:
147 return datetime.fromtimestamp(
148 ((value >> 22) + _SNOWFLAKE_EPOCH_MS) / 1000, tz=timezone.utc
149 )
150 except (OverflowError, OSError, ValueError):
151 return None
152
153
154 def _looks_generated(ids: List[str]) -> bool:
155 """True when ids form a near-uniform arithmetic run.
156
157 Real ranked results are not evenly spaced in time. A fabricated set often
158 is, because a model interpolates a plausible-looking id sequence. Four
159 ids is the minimum used here: three gaps are needed before a near-uniform
160 step reads as generated rather than coincidental.
161 """
162 numeric = []
163 for pid in ids:
164 try:
165 numeric.append(int(pid))
166 except (TypeError, ValueError):
167 return False
168 if len(numeric) < 4:
169 return False
170 numeric.sort()
171 gaps = [b - a for a, b in zip(numeric, numeric[1:])]
172 if any(g <= 0 for g in gaps):
173 return False
174 mean = sum(gaps) / len(gaps)
175 if mean <= 0:
176 return False
177 # Every gap within 5% of the mean is not something real timelines do.
178 return all(abs(g - mean) / mean < 0.05 for g in gaps)
179
180
181 def _clean_handle(value: str) -> str:
182 """Return a grammar-valid handle, or '' when the value is not one."""
183 candidate = str(value or "").strip().lstrip("@")
184 return candidate if _HANDLE_RE.fullmatch(candidate) else ""
185
186
187 # ---------------------------------------------------------------------------
188 # Parser
189 # ---------------------------------------------------------------------------
190
191
192 def _safe_int(value: Any) -> Optional[int]:
193 if value is None:
194 return None
195 try:
196 return int(value)
197 except (ValueError, TypeError):
198 return None
199
200
201 def parse_v2_response(
202 response: Dict[str, Any],
203 topic: str = "",
204 window: Optional[tuple[str, str]] = None,
205 *,
206 id_prefix: str = "XAPI",
207 index_offset: int = 0,
208 seen_ids: Optional[set[str]] = None,
209 ) -> List[Dict[str, Any]]:
210 """Parse an X API v2 search response into the engine's X item shape.
211
212 Output matches the XItem schema used by xai_x and bird_x (id, text, url,
213 author_handle, date, engagement, mentioned_handles, why_relevant,
214 relevance) plus ``post_id`` (the numeric snowflake as a string). The
215 citation URL is rebuilt from the id and username; URL fields in the
216 response are never used. A post whose author is not in
217 ``includes.users`` (or whose username fails the handle grammar) keeps
218 the ``https://x.com/i/status/<id>`` form with an empty handle.
219
220 ``window`` is an optional ``(from_date, to_date)`` pair of YYYY-MM-DD
221 strings; dated posts outside it are dropped. ``seen_ids`` and
222 ``index_offset`` let several calls share one accumulator with unique ids.
223 """
224 items: List[Dict[str, Any]] = []
225 if not isinstance(response, dict):
226 return items
227 if "error" in response:
228 _log("error in response; no items parsed")
229 return items
230
231 data = response.get("data") or []
232 if not isinstance(data, list) or not data:
233 return items
234
235 authors: Dict[str, str] = {}
236 for user in (response.get("includes") or {}).get("users") or []:
237 if isinstance(user, dict) and user.get("id") is not None:
238 authors[str(user["id"])] = _clean_handle(user.get("username", ""))
239
240 from .query import leading_mentions
241
242 window_from, window_to = (window or (None, None))
243 seen = seen_ids if seen_ids is not None else set()
244
245 for tweet in data:
246 if not isinstance(tweet, dict):
247 continue
248 tweet_id = str(tweet.get("id") or "").strip()
249 if not tweet_id.isdigit():
250 continue
251 if tweet_id in seen:
252 continue
253
254 username = authors.get(str(tweet.get("author_id") or ""), "")
255 if username:
256 url = f"https://x.com/{username}/status/{tweet_id}"
257 else:
258 url = f"https://x.com/i/status/{tweet_id}"
259
260 note = tweet.get("note_tweet")
261 text = ""
262 if isinstance(note, dict) and note.get("text"):
263 text = str(note["text"])
264 else:
265 text = str(tweet.get("text") or "")
266 text = text.strip()
267
268 engagement: Optional[Dict[str, Any]] = None
269 metrics = tweet.get("public_metrics") or {}
270 if isinstance(metrics, dict) and metrics:
271 engagement = {
272 "likes": metrics.get("like_count", 0),
273 "reposts": metrics.get("retweet_count", 0),
274 "replies": metrics.get("reply_count", 0),
275 "quotes": metrics.get("quote_count", 0),
276 }
277 bookmarks = _safe_int(metrics.get("bookmark_count"))
278 if bookmarks is not None:
279 engagement["bookmarks"] = bookmarks
280 views = _safe_int(metrics.get("impression_count"))
281 if views is not None:
282 engagement["views"] = views
283
284 date: Optional[str] = None
285 created = str(tweet.get("created_at") or "")
286 if created:
287 m = re.match(r"(\d{4}-\d{2}-\d{2})", created)
288 if m:
289 date = m.group(1)
290 if date and window_from and date < window_from:
291 continue
292 if date and window_to and date > window_to:
293 continue
294
295 seen.add(tweet_id)
296 items.append({
297 "id": f"{id_prefix}{index_offset + len(items) + 1}",
298 "text": text[:500],
299 "url": url,
300 "author_handle": username,
301 "date": date,
302 "engagement": engagement,
303 "mentioned_handles": leading_mentions(text),
304 "why_relevant": "",
305 "relevance": _compute_relevance(topic, text) if topic else 0.5,
306 "post_id": tweet_id,
307 })
308
309 return items
310
311
312 # ---------------------------------------------------------------------------
313 # Query compilation
314 # ---------------------------------------------------------------------------
315
316
317 def _topic_tokens(topic: str, *, preserve_trailing_colon: bool = False) -> List[str]:
318 """Sanitized topic tokens: no quotes, grouping, operators, or negation."""
319 separators = str.maketrans({char: " " for char in _GROUPING_CHARS + _QUOTE_CHARS})
320 cleaned = str(topic or "").translate(separators)
321 tokens: List[str] = []
322 for token in cleaned.split():
323 clean = token.strip(_APOSTROPHES)
324 if preserve_trailing_colon and clean.endswith(":") and clean.count(":") == 1:
325 clean = clean[:-1]
326 if not clean:
327 continue
328 if ":" in clean or clean.startswith("-"):
329 continue
330 if clean.upper() in ("OR", "AND"):
331 continue
332 tokens.append(clean)
333 return tokens
334
335
336 def _compile(tokens: List[str]) -> str:
337 return f'"{" ".join(tokens)}" -is:retweet'
338
339
340 def _compile_keywords(tokens: List[str]) -> str:
341 return " ".join(tokens)
342
343
344 def _fit(tokens: List[str], compile_tokens: Callable[[List[str]], str]) -> str:
345 """Compile *tokens*, dropping trailing ones until under ``MAX_QUERY_CHARS``."""
346 if not tokens:
347 return ""
348 tokens = list(tokens)
349 compiled = compile_tokens(tokens)
350 while len(compiled) > MAX_QUERY_CHARS and len(tokens) > 1:
351 tokens.pop()
352 compiled = compile_tokens(tokens)
353 if len(compiled) > MAX_QUERY_CHARS:
354 # One token longer than the whole budget: keep as much of it as fits.
355 overhead = len(compile_tokens([""]))
356 tokens = [tokens[0][: MAX_QUERY_CHARS - overhead]]
357 compiled = compile_tokens(tokens)
358 return compiled
359
360
361 def build_query(topic: str) -> str:
362 """Compile a topic into one quoted phrase plus ``-is:retweet``.
363
364 Mirrors ``bird_x.build_topic_query`` (grouping characters become spaces,
365 quotes are balanced) and additionally drops every operator-shaped token
366 (anything with a colon, anything starting with ``-``, bare OR/AND) so a
367 topic can never smuggle ``from:``, ``since:``, or a phrase break into the
368 request. The window is never part of the query (see ``_window``). The
369 result stays under ``MAX_QUERY_CHARS``, cut at a token boundary. Returns
370 "" when nothing lexical survives.
371 """
372 return _fit(_topic_tokens(topic), _compile)
373
374
375 def build_keyword_query(topic: str) -> str:
376 """Compile a topic into space-joined keywords (implicit AND), no operators.
377
378 The keyword counterpart of :func:`build_query` for callers that keep
379 X's default any-order keyword matching instead of one exact phrase
380 (``xurl_x``). The same operator safeguards apply, while ordinary trailing
381 colons preserve subject words: bare ``and``/``or`` in any case, colon
382 operators, leading ``-`` negation, grouping and quote characters never
383 reach X, whose v2 grammar rejects a bare lowercase ``and``/``or`` with
384 HTTP 400. Capped at ``MAX_QUERY_CHARS`` on a token boundary. Returns ""
385 when nothing lexical survives.
386 """
387 return _fit(_topic_tokens(topic, preserve_trailing_colon=True), _compile_keywords)
388
389
390 # ---------------------------------------------------------------------------
391 # Window
392 # ---------------------------------------------------------------------------
393
394
395 def _parse_day(value: str) -> Optional[datetime]:
396 try:
397 return datetime.strptime(str(value)[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc)
398 except (TypeError, ValueError):
399 return None
400
401
402 def _iso(when: datetime) -> str:
403 return when.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
404
405
406 def _window(from_date: str, to_date: str) -> tuple[str, str]:
407 """``(start_time, end_time)`` for the request, ISO 8601 with Z.
408
409 ``start_time`` is midnight UTC of ``from_date``; ``end_time`` is the end
410 of ``to_date`` or, when that would be now or later ("today"), now minus a
411 safety margin.
412 """
413 now = _utcnow()
414 start = _parse_day(from_date) or (now - timedelta(days=30))
415 end_day = _parse_day(to_date)
416 latest = now - timedelta(seconds=END_TIME_SAFETY_SECONDS)
417 if end_day is None:
418 end = latest
419 else:
420 end = min(end_day + timedelta(hours=23, minutes=59, seconds=59), latest)
421 if start >= end:
422 start = end - timedelta(days=1)
423 return _iso(start), _iso(end)
424
425
426 def _recent_floor() -> str:
427 """The earliest ``start_time`` recent search accepts, with a margin."""
428 return _iso(
429 _utcnow() - timedelta(days=RECENT_WINDOW_DAYS) + timedelta(seconds=END_TIME_SAFETY_SECONDS)
430 )
431
432
433 # ---------------------------------------------------------------------------
434 # Transport
435 # ---------------------------------------------------------------------------
436
437
438 class _XApiFailure(Exception):
439 """A request failure already reduced to its fixed string.
440
441 ``enrollment`` marks the one 403 that recent search can still serve.
442 The message is always one of the ERR_* literals (or ``xapi: http <n>``),
443 never response text.
444 """
445
446 def __init__(self, message: str, *, enrollment: bool = False):
447 super().__init__(message)
448 self.enrollment = enrollment
449
450
451 def _failure_for(exc: http.HTTPError) -> _XApiFailure:
452 status = getattr(exc, "status_code", None)
453 body = str(getattr(exc, "body", "") or "").lower()
454 if (
455 status == 402
456 or http.classify_failure(message=body) == health.PAYMENT_REQUIRED
457 or any(marker in body for marker in _X_CREDIT_MARKERS)
458 ):
459 return _XApiFailure(ERR_PAYMENT_REQUIRED)
460 if status == 401:
461 return _XApiFailure(ERR_UNAUTHORIZED)
462 if status == 403:
463 enrolled = any(marker in body for marker in _ENROLLMENT_MARKERS)
464 return _XApiFailure(ERR_FORBIDDEN, enrollment=enrolled)
465 if status == 429:
466 return _XApiFailure(ERR_RATE_LIMITED)
467 state = getattr(exc, "outcome_state", None)
468 if status == 408 or state == health.TIMEOUT:
469 return _XApiFailure(ERR_TIMED_OUT)
470 if status:
471 return _XApiFailure(f"xapi: http {status}")
472 if state == health.UNREACHABLE:
473 return _XApiFailure(ERR_UNREACHABLE)
474 return _XApiFailure("xapi: request failed (HTTPError)")
475
476
477 def _get(
478 token: str, url: str, params: Dict[str, Any], deadline: Optional[float] = None,
479 cancel: Any = None,
480 ) -> Dict[str, Any]:
481 """One authenticated GET; every failure surfaces as ``_XApiFailure``.
482
483 ``deadline`` is handed to the transport as its wall deadline, so a
484 request started just before it cannot keep the full per-request timeout
485 and retry cycle: the socket wait and every backoff sleep stop at the
486 deadline (``http.DeadlineExceeded`` -> ``ERR_TIMED_OUT``).
487 """
488 try:
489 response = http.get(
490 url,
491 headers={"Authorization": f"Bearer {token}"},
492 params=params,
493 timeout=TIMEOUT_SECONDS,
494 retries=RETRIES,
495 deadline_monotonic=deadline,
496 **({"cancel": cancel} if cancel is not None else {}),
497 )
498 except http.HTTPError as exc:
499 raise _failure_for(exc) from None
500 except TimeoutError:
501 raise _XApiFailure(ERR_TIMED_OUT) from None
502 except Exception as exc: # noqa: BLE001 - the message must never leak
503 raise _XApiFailure(f"xapi: request failed ({type(exc).__name__})") from None
504 return response if isinstance(response, dict) else {}
505
506
507 def _page_size(count: int) -> int:
508 return max(MIN_PAGE_RESULTS, min(MAX_PAGE_RESULTS, int(count)))
509
510
511 def _search_pages(
512 token: str,
513 url: str,
514 params: Dict[str, Any],
515 count: int,
516 deadline: Optional[float] = None,
517 cancel: Any = None,
518 ) -> Dict[str, Any]:
519 """Follow ``next_token`` until ``count`` posts are collected.
520
521 ``deadline`` is a ``time.monotonic()`` instant: the first page always
522 runs; a later page is skipped once the deadline has passed and the
523 posts collected so far are returned with ``"truncated": True`` so the
524 caller can report the incomplete coverage.
525 """
526 data: List[Dict[str, Any]] = []
527 users: Dict[str, Dict[str, Any]] = {}
528 truncated = False
529 page_params = dict(params)
530 page_params["max_results"] = _page_size(count)
531 # Bound the walk even when every page carries a next_token.
532 max_pages = max(1, -(-count // MIN_PAGE_RESULTS))
533 for page_index in range(max_pages):
534 if cancel is not None and cancel.is_set():
535 if not data:
536 raise _XApiFailure(ERR_TIMED_OUT)
537 truncated = True
538 break
539 if page_index and deadline is not None and time.monotonic() >= deadline:
540 _log(f"search deadline ({DEADLINE_SECONDS}s) reached; keeping {len(data)} posts")
541 truncated = True
542 break
543 # A fresh dict per page: the transport must never see a later
544 # page's next_token on an earlier request.
545 try:
546 response = _get(token, url, dict(page_params), deadline, **({"cancel": cancel} if cancel is not None else {}))
547 except _XApiFailure as exc:
548 if data and str(exc) == ERR_TIMED_OUT:
549 # The budget ran out mid-walk: the pages already collected
550 # are the result, reported as truncated, not a failure.
551 _log(f"search deadline reached mid-walk; keeping {len(data)} posts")
552 truncated = True
553 break
554 raise
555 page = response.get("data") or []
556 if isinstance(page, list):
557 data.extend(t for t in page if isinstance(t, dict))
558 for user in (response.get("includes") or {}).get("users") or []:
559 if isinstance(user, dict) and user.get("id") is not None:
560 users[str(user["id"])] = user
561 next_token = (response.get("meta") or {}).get("next_token")
562 if not next_token or len(data) >= count:
563 break
564 page_params["next_token"] = next_token
565 return {
566 "data": data[:count],
567 "includes": {"users": list(users.values())},
568 "truncated": truncated,
569 }
570
571
572 def _run_search(
573 token: str,
574 query: str,
575 from_date: str,
576 to_date: str,
577 count: int,
578 *,
579 topic: str,
580 id_prefix: str,
581 label: str,
582 deadline: Optional[float] = None,
583 cancel: Any = None,
584 deadline_is_warning: bool = False,
585 ) -> Dict[str, Any]:
586 """Full-archive search with the recent-search fallback.
587
588 ``deadline`` (a ``time.monotonic()`` instant) is shared with the caller's
589 other lanes; without one the search gets its own ``DEADLINE_SECONDS``.
590 A shared deadline that has already passed sends no request at all.
591
592 Returns ``{"items": [...]}`` (plus ``"warning"`` when the window was
593 truncated or the deadline stopped the walk early) or ``{"items": [],
594 "error": <fixed string>}``.
595 """
596 start, end = _window(from_date, to_date)
597 params = {
598 "query": query,
599 "start_time": start,
600 "end_time": end,
601 "sort_order": "recency",
602 "expansions": "author_id",
603 "tweet.fields": "created_at,public_metrics,note_tweet,entities",
604 "user.fields": "username",
605 }
606 cancelled = cancel is not None and cancel.is_set()
607 expired = deadline is not None and time.monotonic() >= deadline
608 if cancelled or expired:
609 if deadline_is_warning:
610 _log(f"{label}: lane budget ({LANE_BUDGET_SECONDS:.0f}s) exhausted before the search started")
611 return {"items": [], "warning": DEADLINE_DETAIL}
612 _log(f"{label}: {ERR_TIMED_OUT}")
613 return {"items": [], "error": ERR_TIMED_OUT}
614 _log(f"Searching: {label}")
615 warnings: List[str] = []
616 if deadline is None:
617 deadline = time.monotonic() + DEADLINE_SECONDS
618 try:
619 # Full-archive search returns HTTP 403 on Basic/Pro projects that are
620 # not enrolled; exclude that probe 403 from http._failure_sink so a
621 # clean recent-search fallback is never misreported as AUTH_FAILED.
622 # Non-enrollment 403s still surface via ERR_FORBIDDEN below.
623 with http.expected_misses(403):
624 response = _search_pages(token, _SEARCH_ALL_URL, params, count, deadline, **({"cancel": cancel} if cancel is not None else {}))
625 except _XApiFailure as exc:
626 if not exc.enrollment:
627 _log(f"{label}: {exc}")
628 return {"items": [], "error": str(exc)}
629 floor = _recent_floor()
630 truncated_window = floor > start
631 if truncated_window:
632 _log(f"{label}: full-archive search not enrolled; retrying recent search ({TRUNCATION_DETAIL})")
633 else:
634 _log(f"{label}: full-archive search not enrolled; retrying recent search")
635 if floor >= end:
636 # The whole window predates what recent search can reach: an
637 # empty, truncated result, never a start_time after end_time.
638 _log(f"{label}: window ends before the recent-search floor; nothing to fetch")
639 return {"items": [], "warning": TRUNCATION_DETAIL}
640 params["start_time"] = max(start, floor)
641 try:
642 response = _search_pages(token, _SEARCH_RECENT_URL, params, count, deadline, **({"cancel": cancel} if cancel is not None else {}))
643 except _XApiFailure as exc2:
644 _log(f"{label}: {exc2}")
645 return {"items": [], "error": str(exc2)}
646 if truncated_window:
647 warnings.append(TRUNCATION_DETAIL)
648 if response.get("truncated"):
649 warnings.append(DEADLINE_DETAIL)
650 items = parse_v2_response(response, topic, (from_date, to_date), id_prefix=id_prefix)
651 result: Dict[str, Any] = {"items": items}
652 if warnings:
653 result["warning"] = "; ".join(warnings)
654 return result
655
656
657 # ---------------------------------------------------------------------------
658 # Public search entry points
659 # ---------------------------------------------------------------------------
660
661
662 def search_x(
663 token: str,
664 query: str,
665 from_date: str,
666 to_date: str,
667 depth: str = "default",
668 deadline: Optional[float] = None,
669 cancel: Any = None,
670 ) -> Dict[str, Any]:
671 """Topic search via X API v2.
672
673 Returns ``{"items": [...]}`` or ``{"items": [], "error": "..."}`` (the
674 xquik shape); ``"warning"`` carries the truncation detail after the
675 recent-search fallback. ``deadline`` is the X chain's shared
676 ``time.monotonic()`` budget; without one the search gets its own
677 ``DEADLINE_SECONDS``.
678 """
679 if not token:
680 return {"items": [], "error": ERR_NO_TOKEN}
681 count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
682 compiled = build_query(query)
683 if not compiled:
684 _log("topic compiled to an empty query after sanitizing")
685 return {"items": [], "error": ERR_EMPTY_QUERY}
686 return _run_search(
687 token, compiled, from_date, to_date, count,
688 topic=query, id_prefix="XAPI", label="topic", deadline=deadline,
689 **({"cancel": cancel} if cancel is not None else {}),
690 )
691
692
693 def is_own_post(url: str, handle: str) -> bool:
694 """True when a post URL is authored by ``handle`` (their own post).
695
696 The ABOUT lanes (here, xquik, the host envelope) drop the subject's own
697 posts so only mentions *by others* remain. Handles both x.com and
698 twitter.com permalinks.
699 """
700 u = (url or "").lower()
701 h = handle.lower().lstrip("@").strip()
702 return bool(h) and (f"x.com/{h}/status" in u or f"twitter.com/{h}/status" in u)
703
704
705
706 def _lane_handle(raw: str, lane: str) -> str:
707 handle = _clean_handle(raw)
708 if not handle:
709 _log(f"skipping {lane} lane for a handle outside the X handle grammar")
710 return handle
711
712
713 _MAX_LANE_WORKERS = 5
714
715
716 def _run_handle_lanes(
717 handles: List[str],
718 search_one: Callable[[str], Dict[str, Any]],
719 *,
720 id_prefix: str,
721 keep: Optional[Callable[[Dict[str, Any], str], bool]] = None,
722 warnings: Optional[List[str]] = None,
723 errors: Optional[List[str]] = None,
724 ) -> List[Dict[str, Any]]:
725 """Run one search per handle on a bounded pool and merge in handle order.
726
727 Per-handle receipts (``"warning"`` on a result, e.g. a deadline stop)
728 are appended to ``warnings`` once each, and per-handle errors
729 (``"error"``, e.g. 401/402/403/429/timeout) are appended to ``errors``
730 once each, so the caller can report incomplete or failed lane coverage
731 instead of presenting it as a clean empty result.
732
733 Mirrors ``bird_x.search_handles``: at most five handles in flight. A
734 fatal auth/payment result stops further handles from being scheduled;
735 whatever was already fetched is kept. Results are merged on the calling
736 thread in ``handles`` order, deduped by post id across handles, and
737 renumbered ``<id_prefix><n>`` so the output is deterministic regardless
738 of completion order. ``keep(item, handle)`` filters a handle's items
739 after the post id is recorded, so a dropped post still dedupes later.
740 """
741 results: List[Optional[Dict[str, Any]]] = [None] * len(handles)
742 if handles:
743 max_workers = min(_MAX_LANE_WORKERS, len(handles))
744 fatal = False
745 with ThreadPoolExecutor(max_workers=max_workers) as pool:
746 pending: Dict[Any, int] = {}
747 next_index = 0
748 while pending or (next_index < len(handles) and not fatal):
749 while next_index < len(handles) and not fatal and len(pending) < max_workers:
750 pending[pool.submit(search_one, handles[next_index])] = next_index
751 next_index += 1
752 done, _ = wait(list(pending), return_when=FIRST_COMPLETED)
753 for future in done:
754 index = pending.pop(future)
755 result = future.result()
756 results[index] = result
757 if result.get("error") in _FATAL_ERRORS:
758 fatal = True # the key itself failed; keep what we have
759
760 items: List[Dict[str, Any]] = []
761 seen_ids: set[str] = set()
762 for handle, result in zip(handles, results):
763 note = (result or {}).get("warning")
764 if note and warnings is not None and note not in warnings:
765 warnings.append(note)
766 err = (result or {}).get("error")
767 if err and errors is not None and err not in errors:
768 errors.append(err)
769 for item in (result or {}).get("items", []):
770 post_id = item.get("post_id", "")
771 if post_id in seen_ids:
772 continue
773 seen_ids.add(post_id)
774 if keep is not None and not keep(item, handle):
775 continue
776 item["id"] = f"{id_prefix}{len(items) + 1}"
777 items.append(item)
778 return items
779
780
781 def search_handles(
782 handles: List[str],
783 topic: str,
784 from_date: str,
785 to_date: str,
786 *,
787 count_per: int = 8,
788 token: str = "",
789 deadline: Optional[float] = None,
790 warnings: Optional[List[str]] = None,
791 errors: Optional[List[str]] = None,
792 cancel: Any = None,
793 ) -> List[Dict[str, Any]]:
794 """FROM lane: posts authored BY each handle (their own timeline).
795
796 The topic is NOT AND'd into the query; it ranks relevance only (mirrors
797 ``xquik.search_handles``). A handle outside the X grammar skips its lane
798 with a receipt line.
799 """
800 if not token or not handles:
801 return []
802 clean = [h for h in (_lane_handle(raw, "from:") for raw in handles) if h]
803
804 def _search_one(handle: str) -> Dict[str, Any]:
805 return _run_search(
806 token, f"from:{handle} -is:retweet", from_date, to_date, count_per,
807 topic=topic, id_prefix="XF", label=f"from:{handle}", deadline=deadline,
808 deadline_is_warning=True,
809 **({"cancel": cancel} if cancel is not None else {}),
810 )
811
812 return _run_handle_lanes(clean, _search_one, id_prefix="XF", warnings=warnings, errors=errors)
813
814
815 def search_mentions(
816 handles: List[str],
817 from_date: str,
818 to_date: str,
819 *,
820 topic: str = "",
821 count_per: int = 5,
822 token: str = "",
823 deadline: Optional[float] = None,
824 warnings: Optional[List[str]] = None,
825 errors: Optional[List[str]] = None,
826 cancel: Any = None,
827 ) -> List[Dict[str, Any]]:
828 """ABOUT lane: posts mentioning each handle, authored by OTHERS.
829
830 The query is ``@handle -from:handle`` and the handle's own posts are
831 dropped again client-side (``is_own_post``) so only third-party mentions
832 remain.
833 """
834 if not token or not handles:
835 return []
836 clean = [h for h in (_lane_handle(raw, "mention") for raw in handles) if h]
837
838 def _search_one(handle: str) -> Dict[str, Any]:
839 return _run_search(
840 token, f"@{handle} -from:{handle} -is:retweet", from_date, to_date, count_per,
841 topic=topic, id_prefix="XA", label=f"@{handle}", deadline=deadline,
842 deadline_is_warning=True,
843 **({"cancel": cancel} if cancel is not None else {}),
844 )
845
846 return _run_handle_lanes(
847 clean, _search_one, id_prefix="XA",
848 keep=lambda item, handle: not is_own_post(item.get("url", ""), handle),
849 warnings=warnings,
850 errors=errors,
851 )
852
852 lines PYTHON