返回 last30days-skill
jobs.py
根目录 / skills / last30days / scripts / lib / jobs.py
1 """Public jobs/careers retrieval for Hiring Signals.
2
3 Tiered strategy (each tier degrades gracefully; the artifact records which
4 tier produced results so synthesis knows the confidence level):
5
6 - Tier 1 - direct ATS API. The company's own board is authoritative and
7 structured. Discovery is careers-page-first: fetch the careers page and read
8 the provider + exact slug straight off the embed/link, then call that API.
9 We only emit ATS results when a call actually returns a non-empty board, so a
10 bad slug guess never produces fabricated coverage. Slug-probing is a fallback,
11 never the entry point.
12 A careers page on a hiring platform (Oracle Recruiting Cloud, Jibe, Phenom,
13 TalentBrew, Eightfold; ``lib.job_boards.detect``) is read through that
14 platform's public listing endpoint. A reader that fails falls to the
15 roster tier, then the web tier, and the artifact says so.
16 - Tier 1b - roster. A job sitemap the careers site lists in its robots.txt
17 (``lib.job_boards.sitemap``): titles only, no posting dates.
18 - Tier 2 - careers page found, no supported ATS API. Parse schema.org
19 ``JobPosting`` JSON-LD (emitted by most careers pages for Google Jobs SEO,
20 regardless of ATS).
21 - Tier 3 - generic web search. Last resort, noisy, clearly low-confidence.
22 """
23
24 from __future__ import annotations
25
26 import importlib
27 import json
28 import re
29 import threading
30 import time
31 from concurrent.futures import Future, ThreadPoolExecutor
32 from concurrent.futures import TimeoutError as FutureTimeout
33 from contextvars import ContextVar, copy_context
34 from html import unescape
35 from typing import Any, Callable
36 from urllib.parse import quote, urlencode, urljoin, urlparse
37
38 from . import dates, grounding, health, http, jobs_digest, jobs_story, jobs_teams, log
39 from .job_boards import detect as board_detect
40 from .job_boards import robots as board_robots
41
42
43 ATS_PROVIDER_GREENHOUSE = "greenhouse"
44 ATS_PROVIDER_ASHBY = "ashby"
45 ATS_PROVIDER_LEVER = "lever"
46 ATS_PROVIDER_WORKABLE = "workable"
47 ATS_PROVIDER_SMARTRECRUITERS = "smartrecruiters"
48 ATS_PROVIDER_WORKDAY = "workday"
49
50 # Workday's public listing endpoint serves 20 rows per call and stops at 2,000
51 # rows however large the board is.
52 WORKDAY_PAGE_SIZE = 20
53 WORKDAY_ROW_CEILING = 2000
54 # One page takes about a second, so a full 2,000-row board is about 100 s read
55 # one page at a time. Eight at once reads it in roughly 15 s.
56 WORKDAY_MAX_WORKERS = 8
57 # Wall time allowed for the whole lane on one topic: finding the careers page,
58 # reading the board off it, the listing pages and the detail calls. A
59 # comparison run gives each entity an equal share of it. When it is spent the
60 # lane returns what it has read. Descriptions and true posted dates cost one
61 # call per Workday role, so they are fetched only for the roles the digest
62 # selected.
63 JOBS_BUDGET_SECONDS = 45.0
64 # The same allowance under its first name, for a board read on its own.
65 WORKDAY_BUDGET_SECONDS = JOBS_BUDGET_SECONDS
66 # Longest one request may take, so that one host that never answers cannot
67 # spend the budget: a careers page on the company's known site, a page on a
68 # domain only guessed from its name, and one call to a board's API.
69 PAGE_TIMEOUT_SECONDS = 8
70 GUESS_TIMEOUT_SECONDS = 4
71 API_TIMEOUT_SECONDS = 10
72
73 # SmartRecruiters serves at most 100 rows per call. Its board is read to the
74 # same row ceiling and under the same time budget as a Workday board.
75 SMARTRECRUITERS_PAGE_SIZE = 100
76 SMARTRECRUITERS_ROW_CEILING = 2000
77
78 # Company-run job boards. Most large companies run their careers site on one
79 # of a few hiring platforms, and the careers page names it: such a board is
80 # found by detection (``lib.job_boards.detect``) and read by that platform's
81 # reader, with no entry here. This table is only for the few companies whose
82 # board cannot be found from their official site: a job site of their own
83 # with no platform behind it (Apple, Amazon, Google), or a careers page that
84 # answers automated requests with a block while its hosted board does not
85 # (Intel, Salesforce). Each is read only when the run knows the company's
86 # official site, and the site's host is what picks the board, so a reader is
87 # never reached by guessing a domain or matching a name.
88 COMPANY_PROVIDER_APPLE = "apple"
89 COMPANY_PROVIDER_AMAZON = "amazon"
90 COMPANY_PROVIDER_EIGHTFOLD = "eightfold"
91 COMPANY_PROVIDER_GOOGLE = "google"
92 COMPANY_PROVIDER_IBM = "ibm"
93 # Platforms found by detection, read by ``lib.job_boards``.
94 PLATFORM_PROVIDER_ORACLE = board_detect.PROVIDER_ORACLE
95 PLATFORM_PROVIDER_JIBE = board_detect.PROVIDER_JIBE
96 PLATFORM_PROVIDER_PHENOM = board_detect.PROVIDER_PHENOM
97 PLATFORM_PROVIDER_TALENTBREW = board_detect.PROVIDER_TALENTBREW
98 PLATFORM_PROVIDER_KULA = board_detect.PROVIDER_KULA
99 SITEMAP_PROVIDER = "sitemap"
100 _GOOGLE_BOARD = {"name": "Google", "provider": COMPANY_PROVIDER_GOOGLE, "board": "www.google.com"}
101 # Official-site host -> the board that site's company runs. ``name`` is how
102 # the footer names the company when its board cannot be read. A ``workday``
103 # entry's ``board`` is the board token ``detect_ats`` would build.
104 COMPANY_BOARDS: dict[str, dict[str, str]] = {
105 "apple.com": {"name": "Apple", "provider": COMPANY_PROVIDER_APPLE, "board": "jobs.apple.com"},
106 "amazon.com": {"name": "Amazon", "provider": COMPANY_PROVIDER_AMAZON, "board": "www.amazon.jobs"},
107 "google.com": _GOOGLE_BOARD,
108 "about.google": _GOOGLE_BOARD,
109 "abc.xyz": _GOOGLE_BOARD,
110 # intel.com and its jobs host answer every request with a 403.
111 "intel.com": {"name": "Intel", "provider": ATS_PROVIDER_WORKDAY, "board": "intel.wd1/External"},
112 # careers.ibm.com answers an empty 202 to pages and sitemaps alike; the
113 # search page reads IBM's own search API.
114 "ibm.com": {"name": "IBM", "provider": COMPANY_PROVIDER_IBM, "board": "careers.ibm.com"},
115 # Salesforce's job search loads its roles in the browser from Workday.
116 "salesforce.com": {
117 "name": "Salesforce", "provider": ATS_PROVIDER_WORKDAY,
118 "board": "salesforce.wd12/External_Career_Site",
119 },
120 }
121 # Official-site host -> the careers page to read first, for a company whose
122 # careers site is on a domain of its own that its official site does not link
123 # in a way the lane can follow. The page is then read like any careers page.
124 CAREERS_PAGES: dict[str, str] = {
125 "disney.com": "https://join.disneycareers.com/global/en",
126 "thewaltdisneycompany.com": "https://join.disneycareers.com/global/en",
127 # join.nothing.tech is a static copy of this Kula board with no role
128 # data, and careers.nothing.tech embeds a Greenhouse board that is gone.
129 "nothing.tech": "https://careers.kula.ai/nothing",
130 }
131 # Official-site hosts whose job site is not read: its site prohibits
132 # automated collection, or it answers every automated request (pages,
133 # robots.txt and sitemap alike) with a block page. No request is sent to them.
134 UNREADABLE_JOB_SITES: dict[str, dict[str, str]] = {
135 "meta.com": {"name": "Meta", "reason": "its site prohibits automated collection"},
136 "metacareers.com": {"name": "Meta", "reason": "its site prohibits automated collection"},
137 "tesla.com": {"name": "Tesla", "reason": "it answers every automated request with a block page"},
138 }
139 # Share of the lane's remaining time a company board's listing leaves for the
140 # role text of the roles the digest selects, so a long list never costs the
141 # digest its text.
142 DETAIL_SHARE = 1 / 3
143 # Story search: before a board's newest-first read, the board is searched for
144 # the run's story terms. A board with a keyword search is asked once per term,
145 # up to this many calls per company (every site of a Workday tenant counts as
146 # one company), fewer in a comparison. Eightfold answers 429 after two or
147 # three calls, so it is asked once.
148 STORY_CALLS_PER_COMPANY = 4
149 EIGHTFOLD_STORY_CALLS = 1
150 STORY_TIMEOUT_SECONDS = 10
151 # Story calls share this part of the time left when they start, so the
152 # newest-first read always keeps the rest.
153 STORY_SHARE = 1 / 3
154 # A company board is read newest first, a bounded number of pages at once,
155 # to its end or its ceiling. At about half a second a page, sixteen at once
156 # read Apple's 6,500 rows (20 a page) in about 20 s, inside the listing's
157 # share of the budget; Amazon (100 a page) and Oracle (200) take less.
158 COMPANY_BOARD_ROW_CEILING = 7000
159 COMPANY_BOARD_MAX_WORKERS = 16
160 AMAZON_PAGE_SIZE = 100
161 # Amazon's search reports at most this many hits and pages no further.
162 AMAZON_HITS_CAP = 10_000
163 APPLE_PAGE_SIZE = 20
164 EIGHTFOLD_PAGE_SIZE = 10
165 # The digest picks 40 roles; ten times that is enough to choose from.
166 EIGHTFOLD_ROW_CEILING = 400
167 # Apple's details call usually answers in 2 to 7 seconds, but about one call
168 # in four stalls; a second attempt after a short limit nearly always answers.
169 APPLE_DETAIL_TIMEOUT_SECONDS = 6
170 # Apple's retail store team. Its roles are counted on the board and never
171 # chosen for the digest: the newest pages are almost all retail.
172 APPLE_RETAIL_TEAM = "APPST"
173
174 # Detection patterns: map an ATS embed/link found on a careers page to
175 # (provider, slug). The published slug is authoritative - this is why discovery
176 # is careers-page-first rather than blind probing.
177 _ATS_LINK_PATTERNS: list[tuple[str, str]] = [
178 (ATS_PROVIDER_ASHBY, r"(?:jobs|api)\.ashbyhq\.com/(?:posting-api/job-board/)?([A-Za-z0-9_.-]+)"),
179 (ATS_PROVIDER_GREENHOUSE, r"boards(?:-api)?\.greenhouse\.io/(?:v1/boards/|embed/job_board\?for=)?([A-Za-z0-9_.-]+)"),
180 (ATS_PROVIDER_GREENHOUSE, r"job-boards\.greenhouse\.io/([A-Za-z0-9_.-]+)"),
181 (ATS_PROVIDER_GREENHOUSE, r"greenhouse\.io/embed/job_board\?for=([A-Za-z0-9_.-]+)"),
182 (ATS_PROVIDER_LEVER, r"(?:jobs\.lever\.co|api\.lever\.co/v0/postings)/([A-Za-z0-9_.-]+)"),
183 (ATS_PROVIDER_WORKABLE, r"apply\.workable\.com/(?:api/v[0-9]+/accounts/)?([A-Za-z0-9_.-]+)"),
184 (ATS_PROVIDER_WORKABLE, r"(?<![A-Za-z0-9_-])([A-Za-z0-9_-]{1,63})\.workable\.com"),
185 (ATS_PROVIDER_SMARTRECRUITERS, r"(?:careers|jobs)\.smartrecruiters\.com/([A-Za-z0-9_.-]+)"),
186 (ATS_PROVIDER_SMARTRECRUITERS, r"api\.smartrecruiters\.com/v1/companies/([A-Za-z0-9_.-]+)"),
187 # Workday needs three parts to rebuild its endpoints: tenant, host number
188 # and site. The site may follow a locale segment such as /en-US/.
189 (
190 ATS_PROVIDER_WORKDAY,
191 r"(?<![A-Za-z0-9_-])([A-Za-z0-9_-]{1,63})\.(wd[0-9]+)\.myworkdayjobs\.com/(?:[a-z]{2}-[A-Za-z]{2}/)?([A-Za-z0-9_-]+)",
192 ),
193 # Kula is read by its platform reader, under the slug the link names.
194 (PLATFORM_PROVIDER_KULA, board_detect.KULA_BOARD_LINK),
195 ]
196
197 # The hosts a board URL may be on: only these are read as a board's address.
198 _BOARD_DOMAINS = (
199 "greenhouse.io", "ashbyhq.com", "lever.co", "workable.com",
200 "smartrecruiters.com", "myworkdayjobs.com",
201 )
202 # Shared multi-tenant ATS and hiring-platform domains whose sitemaps can list
203 # roles for companies other than the target; never read as an owned sitemap.
204 _SHARED_PLATFORM_DOMAINS = (
205 *_BOARD_DOMAINS,
206 "kula.ai",
207 "oraclecloud.com",
208 "eightfold.ai",
209 )
210 SUPPORTED_SYSTEMS = "Greenhouse, Ashby, Lever, Workable, SmartRecruiters and Workday"
211 # Hiring platforms read off a careers page on the company's own site.
212 PLATFORM_SYSTEMS = "Oracle Recruiting Cloud, Jibe, Phenom, TalentBrew, Eightfold and Kula"
213
214 # Tokens that show up in ATS URLs but are never real board slugs.
215 _SLUG_STOPWORDS = {"embed", "job_board", "v1", "v0", "api", "posting-api", "boards", "jobs", "job-boards", "www", "wday"}
216
217
218 class LaneBudget:
219 """The wall-clock allowance for everything the lane does for one topic.
220
221 One budget covers every company tried for the topic and every step:
222 careers pages, board detection, listing pages and detail calls. Each step
223 asks how long it may still take, and a step that finds no time left says
224 so with ``stop``. ``slow`` names what did not answer in its own time, so a
225 lane that ends with nothing can say where the time went.
226 """
227
228 def __init__(
229 self,
230 seconds: float = JOBS_BUDGET_SECONDS,
231 *,
232 clock: Callable[[], float] | None = None,
233 ) -> None:
234 self._lock = threading.RLock()
235 self.clock = clock or time.monotonic
236 self.seconds = float(seconds)
237 self.started = self.clock()
238 self.deadline = self.started + self.seconds
239 # Finding a board may be given less than the whole budget, so that a
240 # later company still has time; reading a found board has all of it.
241 self._step_deadline = self.deadline
242 self.slow: list[str] = []
243 self._stopped_at = ""
244 # Board APIs that reached their own request limit while the lane
245 # still had time: that call's failure, not the lane's.
246 self.unanswered: list[str] = []
247 # Set once the lane reached its answer for the topic, so a second
248 # pass of the same run does not ask the same hosts again.
249 self._settled = False
250 # Careers page URL -> the address that answered it, after redirects.
251 self.landed: dict[str, str] = {}
252 # Hosts that gave no answer at all, so no later step asks them again.
253 self.unreachable: set[str] = set()
254
255 @property
256 def step_deadline(self) -> float:
257 with self._lock:
258 return self._step_deadline
259
260 @step_deadline.setter
261 def step_deadline(self, value: float) -> None:
262 with self._lock:
263 self._step_deadline = value
264
265 @property
266 def stopped_at(self) -> str:
267 with self._lock:
268 return self._stopped_at
269
270 @stopped_at.setter
271 def stopped_at(self, value: str) -> None:
272 with self._lock:
273 self._stopped_at = value
274
275 @property
276 def settled(self) -> bool:
277 with self._lock:
278 return self._settled
279
280 @settled.setter
281 def settled(self, value: bool) -> None:
282 with self._lock:
283 self._settled = bool(value)
284
285 def remaining(self) -> float:
286 with self._lock:
287 return max(0.0, min(self.deadline, self._step_deadline) - self.clock())
288
289 def spent(self) -> bool:
290 with self._lock:
291 return self.clock() >= self.deadline
292
293 def limit_discovery(self, seconds: float | None) -> None:
294 with self._lock:
295 self._step_deadline = (
296 self.deadline if seconds is None
297 else min(self.deadline, self.clock() + max(0.0, seconds))
298 )
299
300 def note_slow(self, what: str) -> None:
301 with self._lock:
302 if what and what not in self.slow:
303 self.slow.append(what)
304
305 def note_unanswered(self, detail: str) -> None:
306 with self._lock:
307 if detail:
308 self.unanswered.append(detail)
309
310 def has_unanswered(self, detail: str | None = None) -> bool:
311 with self._lock:
312 if detail is None:
313 return bool(self.unanswered)
314 return detail in self.unanswered
315
316 def unanswered_snapshot(self) -> list[str]:
317 with self._lock:
318 return list(self.unanswered)
319
320 def record_landed(self, url: str, landed_url: str) -> None:
321 with self._lock:
322 self.landed[url] = landed_url
323
324 def get_landed(self, url: str, default: str | None = None) -> str | None:
325 with self._lock:
326 return self.landed.get(url, default)
327
328 def mark_unreachable(self, hosts: set[str] | list[str]) -> None:
329 with self._lock:
330 self.unreachable.update(hosts)
331
332 def is_unreachable(self, host: str) -> bool:
333 with self._lock:
334 return host in self.unreachable
335
336 def stop(self, step: str) -> None:
337 """Record the first step that found no time left."""
338 with self._lock:
339 if not self._stopped_at:
340 self._stopped_at = step
341
342 def reason(self) -> str:
343 """Where the time went, for a lane that ran out of it."""
344 with self._lock:
345 text = (
346 f"jobs lane ran out of time ({self.seconds:g}s budget)" if self.spent()
347 else f"jobs search used up its share of the lane's {self.seconds:g}s"
348 )
349 if self._stopped_at:
350 text += f" before {self._stopped_at}"
351 if self.slow:
352 text += "; slow: " + ", ".join(self.slow[:4])
353 if len(self.slow) > 4:
354 text += f" and {len(self.slow) - 4} more"
355 return text
356
357
358 _BUDGET: ContextVar[LaneBudget | None] = ContextVar("last30days_jobs_budget", default=None)
359
360
361 def _clock() -> Callable[[], float]:
362 budget = _BUDGET.get()
363 return budget.clock if budget is not None else time.monotonic
364
365
366 def _out_of_time(step: str) -> bool:
367 """Whether the lane's budget leaves no time for ``step``; records it if so."""
368 budget = _BUDGET.get()
369 if budget is None or budget.remaining() > 0:
370 return False
371 budget.stop(step)
372 return True
373
374
375 def _request_seconds(timeout: float, attempts: int = 1) -> float:
376 """The longest one call may take in all: each attempt's timeout and the
377 pause ``lib.http`` takes between attempts."""
378 return timeout * attempts + http.RETRY_DELAY * sum(range(1, attempts))
379
380
381 def _bounds(timeout: float, attempts: int = 1) -> dict[str, Any]:
382 """The per-attempt timeout and the call's hard deadline.
383
384 ``timeout`` only reaches each socket operation, so a host that stalls in
385 DNS or sends a byte now and then could hold a request far longer. The
386 hard deadline is the earlier of the call's own limit and what is left of
387 the lane's budget, and ``lib.http`` stops waiting there whatever the
388 socket is doing. Without a budget the call's own limit is the deadline.
389 """
390 seconds = _request_seconds(timeout, attempts)
391 budget = _BUDGET.get()
392 if budget is not None:
393 seconds = min(seconds, budget.remaining())
394 return {"timeout": timeout, "deadline_monotonic": time.monotonic() + seconds}
395
396
397 def _note_slow(what: str) -> None:
398 budget = _BUDGET.get()
399 if budget is not None:
400 budget.note_slow(what)
401
402
403 def _within_budget(call: Callable[[], Any], step: str, default: Any) -> Any:
404 """Run a call that takes no deadline of its own, waiting only as long as
405 the budget allows. ``default`` is returned when the time runs out."""
406 budget = _BUDGET.get()
407 if budget is None:
408 return call()
409 if _out_of_time(step):
410 return default
411 future: Future = Future()
412 context = copy_context()
413
414 def worker() -> None:
415 try:
416 future.set_result(context.run(call))
417 except BaseException as exc: # handed to the waiting caller
418 future.set_exception(exc)
419
420 threading.Thread(target=worker, daemon=True).start()
421 try:
422 return future.result(timeout=budget.remaining())
423 except FutureTimeout:
424 budget.note_slow(f"{step} did not finish")
425 budget.stop(f"the end of {step}")
426 return default
427
428
429 class StorySearch:
430 """The story terms one company's boards are searched for, and the calls
431 and time that search may still use.
432
433 ``calls`` is how many server-side searches are left for the company. The
434 deadline is fixed by the first story call and shared by every call after
435 it: ``STORY_SHARE`` of the lane's time left at that moment.
436 """
437
438 def __init__(self, terms: list[str], *, calls: int) -> None:
439 self.terms = list(terms)
440 self.calls = calls
441 self.deadline: float | None = None
442
443
444 _STORY: ContextVar[StorySearch | None] = ContextVar("last30days_jobs_story", default=None)
445
446
447 def _story_terms() -> list[str]:
448 story = _STORY.get()
449 return story.terms if story is not None else []
450
451
452 def _story_search_for(config: dict[str, Any], entity_count: int = 1) -> StorySearch:
453 """The run's story terms (``_jobs_story_terms``) and its call cap,
454 scaled down by the number of entities a comparison reads."""
455 terms = [str(term) for term in config.get("_jobs_story_terms") or [] if str(term).strip()]
456 entities = max(1, entity_count, int(config.get("_comparison_entity_count") or 1))
457 return StorySearch(terms, calls=max(1, STORY_CALLS_PER_COMPANY // entities))
458
459
460 # Boards whose own search is asked for each story term, by provider: given
461 # the board (a Workday token, else the board's entry), the term and the
462 # call's hard deadline, each returns the rows found. Named like the readers.
463 _STORY_SEARCHERS: dict[str, str] = {
464 ATS_PROVIDER_WORKDAY: "search_workday_story",
465 COMPANY_PROVIDER_AMAZON: "search_amazon_story",
466 COMPANY_PROVIDER_APPLE: "search_apple_story",
467 COMPANY_PROVIDER_EIGHTFOLD: "search_eightfold_story",
468 PLATFORM_PROVIDER_JIBE: "jibe:search_story",
469 }
470 # Searches whose rows carry the role's full text: a row is kept only when
471 # that text names the term. Rows from the others carry little or no text,
472 # so their board's match is taken as it is.
473 _STORY_TEXT_CHECKED = frozenset({COMPANY_PROVIDER_AMAZON, PLATFORM_PROVIDER_JIBE})
474 # Boards read whole: their rows are matched against the terms where they are.
475 _STORY_LOCAL = frozenset({
476 ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER,
477 PLATFORM_PROVIDER_KULA, SITEMAP_PROVIDER,
478 })
479
480
481 def _story_text(item: dict[str, Any]) -> str:
482 return f"{item.get('title') or ''}\n{item.get('description_blocks') or item.get('description') or ''}"
483
484
485 def _story_key(item: dict[str, Any]) -> str:
486 """What makes a story row and a board row one role: Workday's job path
487 (the same on every site of a tenant), Apple's role page (one row per
488 location shares it), else the row's ID."""
489 if item.get("provider") == ATS_PROVIDER_WORKDAY:
490 return _workday_job_key(item)
491 if item.get("provider") == COMPANY_PROVIDER_APPLE:
492 return str(item.get("url") or "")
493 return str(item.get("id") or item.get("url") or "")
494
495
496 def _story_record(*, ran: bool, terms: list[str], partial: bool = False) -> dict[str, Any]:
497 """What a board's story search did: whether it ran, the terms it
498 searched, and ``story_partial`` when a failed call, a 429, a timeout or
499 the story deadline left a term unsearched. ``matches`` is
500 filled in once the rows are tagged."""
501 return {"ran": ran, "terms": list(terms), "matches": 0, "story_partial": partial}
502
503
504 def _search_story(provider: str, targets: list[Any]) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
505 """Ask a board's own search for each story term, before its newest-first read.
506
507 ``targets`` are what the provider's searcher is given: each site of a
508 Workday tenant, or the board's entry. Calls go one at a time, sites in
509 order and each site's terms in order, until the company's calls are used
510 (one on Eightfold) or the story deadline passes. A 429 or a timeout ends
511 the story search for the board. Every row found carries ``story_term``;
512 a role found by two calls is kept once. Returns ``(rows, record)``, the
513 record None when the run has no story terms.
514 """
515 story = _STORY.get()
516 if story is None or not story.terms:
517 return [], None
518 name = _STORY_SEARCHERS.get(provider)
519 if name is None:
520 return [], _story_record(ran=False, terms=[])
521 clock = _clock()
522 if story.deadline is None:
523 budget = _BUDGET.get()
524 left = budget.remaining() if budget is not None else JOBS_BUDGET_SECONDS
525 story.deadline = clock() + left * STORY_SHARE
526 search = _named(name)
527 allowed = min(story.calls, EIGHTFOLD_STORY_CALLS) if provider == COMPANY_PROVIDER_EIGHTFOLD else story.calls
528 pairs = [(target, term) for target in targets for term in story.terms][:max(0, allowed)]
529 rows: list[dict[str, Any]] = []
530 seen: set[str] = set()
531 searched: list[str] = []
532 partial = False
533 for target, term in pairs:
534 left = story.deadline - clock()
535 if left <= 0:
536 partial = True
537 break
538 story.calls -= 1
539 try:
540 # A failed story call is said by ``story_partial``, not counted
541 # among the run's failures: the board's own read still follows.
542 with http.capture_failures():
543 found = search(
544 target, term,
545 deadline_monotonic=time.monotonic() + min(left, STORY_TIMEOUT_SECONDS),
546 )
547 except http.HTTPError as exc:
548 partial = True
549 if exc.status_code == 429 or exc.outcome_state == health.TIMEOUT:
550 break
551 continue
552 except ValueError: # BoardShapeError, bad JSON
553 partial = True
554 continue
555 if term not in searched:
556 searched.append(term)
557 for row in found:
558 if provider in _STORY_TEXT_CHECKED and not jobs_story.matches(term, _story_text(row)):
559 continue
560 key = _story_key(row)
561 if key and key not in seen:
562 seen.add(key)
563 # The order the board's search returned it, which the
564 # digest keeps among one term's roles.
565 rows.append({**row, "story_term": term, "story_rank": len(rows)})
566 if partial:
567 log.source_log(
568 "Jobs", f"story search on the {provider} board stopped early "
569 f"({len(searched)} of {len(story.terms)} terms searched); its newest-first read follows",
570 tty_only=False,
571 )
572 # A board whose every story call failed was never searched: "not run", not "no matches".
573 return rows, _story_record(ran=bool(searched), terms=searched, partial=partial)
574
575
576 def _tag_story_matches(items: list[dict[str, Any]], terms: list[str]) -> None:
577 """Mark each row of a board read whole with the first story term its
578 title or description names."""
579 for item in items:
580 text = _story_text(item)
581 term = next((term for term in terms if jobs_story.matches(term, text)), None)
582 if term is not None:
583 item["story_term"] = term
584
585
586 def _merge_story_rows(
587 items: list[dict[str, Any]], found: list[dict[str, Any]],
588 ) -> list[dict[str, Any]]:
589 """Tag the board rows a story search also found, and return the story
590 rows the board's read did not reach. Those extras are offered to the
591 digest and never added to the board's rows or counts."""
592 by_key = {_story_key(item): item for item in items}
593 extras: list[dict[str, Any]] = []
594 for row in found:
595 board_row = by_key.get(_story_key(row))
596 if board_row is None:
597 extras.append(row)
598 elif not board_row.get("story_term"):
599 board_row["story_term"] = row["story_term"]
600 board_row["story_rank"] = row["story_rank"]
601 return extras
602
603
604 def _local_story_record(items: list[dict[str, Any]]) -> dict[str, Any] | None:
605 """Match the story terms against the rows of a board read whole."""
606 terms = _story_terms()
607 if not terms:
608 return None
609 _tag_story_matches(items, terms)
610 record = _story_record(ran=True, terms=terms)
611 record["matches"] = _story_matches(items)
612 return record
613
614
615 def _story_matches(items: list[dict[str, Any]]) -> int:
616 """Story-matched roles the digest may show."""
617 return sum(1 for item in items if item.get("story_term") and not item.get("digest_excluded"))
618
619
620 def search_jobs(
621 company: str,
622 date_range: tuple[str, str],
623 config: dict[str, Any],
624 *,
625 depth: str = "default",
626 web_backend: str = "auto",
627 explicit: bool = False,
628 site: str = "",
629 entity_count: int = 1,
630 budget: LaneBudget | None = None,
631 discovery_seconds: float | None = None,
632 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
633 """Fetch public job postings for a company via the tiered strategy.
634
635 ``site`` is the company's official site when it is known; its careers page
636 is the only one tried, and a domain is guessed from the company's name
637 only when no site is known. ``entity_count`` is the number of
638 entities a comparison run is fetching at once.
639
640 ``budget`` is the lane's wall-clock allowance; a caller that tries more
641 than one company for a topic passes the same one each time, and may cap
642 the time spent finding this company's board with ``discovery_seconds``.
643 Without one the call gets ``JOBS_BUDGET_SECONDS``, shared between the
644 entities of a comparison. When the budget is spent the call returns what
645 it has: the rows read so far, or nothing with the reason under
646 ``_source_outcome``.
647 """
648 company = company.strip()
649 if not company:
650 return [], {}
651 shared = budget is not None
652 if budget is None:
653 budget = LaneBudget(JOBS_BUDGET_SECONDS / max(1, entity_count))
654 budget.limit_discovery(discovery_seconds)
655 token = _BUDGET.set(budget)
656 story_token = _STORY.set(_story_search_for(config, entity_count))
657 try:
658 items, artifact = _search_jobs(
659 company, date_range, config,
660 web_backend=web_backend, explicit=explicit, site=site, budget=budget,
661 )
662 finally:
663 _STORY.reset(story_token)
664 _BUDGET.reset(token)
665 budget.limit_discovery(None)
666 # A caller that tries several companies on one budget says once, for all
667 # of them, that none has a board (``log_no_board``).
668 return items, _with_budget_outcome(items, artifact, budget, company, quiet=shared)
669
670
671 def _with_budget_outcome(
672 items: list[dict[str, Any]],
673 artifact: dict[str, Any],
674 budget: LaneBudget,
675 company: str,
676 *,
677 quiet: bool = False,
678 ) -> dict[str, Any]:
679 """Say so when the budget, not the board, ended the lane.
680
681 With nothing read the reason is the lane's outcome; with rows it rides
682 along as a note. A lane that looked everywhere in time and found no
683 supported board says only that, and reports no failure.
684 """
685 if artifact.get("tier") == "ats":
686 return artifact
687 if budget.stopped_at or budget.spent():
688 reason = f"{company}: {budget.reason()}"
689 log.source_log("Jobs", reason, tty_only=False)
690 artifact = dict(artifact)
691 if items:
692 artifact["_source_outcome_detail"] = reason
693 else:
694 artifact["_source_outcome"] = {
695 "state": health.TIMEOUT, "detail": reason, "attempted": True,
696 }
697 # Only the lane's own budget running out means a second pass
698 # would run out again. A share of it running out, for one of
699 # several companies, leaves the rest of the budget to a retry.
700 if budget.spent():
701 artifact["_source_out_of_time"] = True
702 return artifact
703 unanswered = budget.unanswered_snapshot()
704 if unanswered and not items:
705 # Time was left, but a board's API never answered: the lane cannot
706 # say there is no board. Named, and open to a retry.
707 reason = f"{company}: {'; '.join(unanswered[:4])}"
708 log.source_log("Jobs", reason, tty_only=False)
709 return {
710 **artifact,
711 "_source_outcome": {"state": health.TIMEOUT, "detail": reason, "attempted": True},
712 }
713 if (
714 artifact.get("tier") == "web" and not items and not quiet
715 and not artifact.get("job_site_unreadable")
716 ):
717 log_no_board([company])
718 return artifact
719
720
721 def log_no_board(companies: list[str]) -> None:
722 """The lane's one line for a topic none of whose companies has a board
723 it can read. Not a failure: the run goes on without jobs."""
724 first, *rest = companies
725 also = f" (also tried: {', '.join(rest)})" if rest else ""
726 log.source_log(
727 "Jobs",
728 f"no supported job board found for {first}{also}; the lane reads "
729 f"{SUPPORTED_SYSTEMS}, and {PLATFORM_SYSTEMS} on a careers page",
730 tty_only=False,
731 )
732
733
734 def _registry_entry(site: str) -> tuple[str, dict[str, str]] | None:
735 """The registry entry for a known official site: ``("board", entry)`` for a
736 company board the lane reads, ``("unreadable", entry)`` for a job site it
737 does not, or None when the site is in neither."""
738 host = _host(site) if site else ""
739 if not host:
740 return None
741 for kind, table in (("board", COMPANY_BOARDS), ("unreadable", UNREADABLE_JOB_SITES)):
742 for key, entry in table.items():
743 if _same_site(host, key):
744 return kind, {**entry, "site": key}
745 return None
746
747
748 def _job_site_unreadable(
749 company: str,
750 date_range: tuple[str, str],
751 config: dict[str, Any],
752 entry: dict[str, str],
753 reason: str,
754 *,
755 attempted: list[str],
756 web_backend: str,
757 explicit: bool,
758 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
759 """The lane's answer when the company's job site is known and not read.
760
761 Says so once, then runs the web tier as any run without a board does. No
762 careers page is fetched and no hosted-system slug is guessed.
763 """
764 name = entry.get("name") or company
765 log.source_log(
766 "Jobs", f"{jobs_digest.unreadable_job_site_line(name)} ({entry.get('site', '')}: {reason})",
767 tty_only=False,
768 )
769 items, artifact = _web_tier(
770 company, date_range, config, attempted=attempted, web_backend=web_backend,
771 explicit=explicit,
772 )
773 artifact["job_site_unreadable"] = name
774 artifact["job_site_unreadable_reason"] = reason
775 return items, artifact
776
777
778 def _web_tier(
779 company: str,
780 date_range: tuple[str, str],
781 config: dict[str, Any],
782 *,
783 attempted: list[str],
784 web_backend: str,
785 explicit: bool,
786 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
787 """Tier 3: a generic web search for postings (noisy, low-confidence)."""
788 fallback_items, artifact = _within_budget(
789 lambda: search_jobs_web(company, date_range, config, backend=web_backend),
790 "the web search for jobs pages",
791 ([], {}),
792 ) if web_backend != "none" else ([], {})
793 artifact = dict(artifact or {})
794 artifact.setdefault("attempted", attempted)
795 artifact.update({
796 "label": artifact.get("label", "jobs"),
797 "company": company,
798 "tier": "web",
799 "explicit": explicit,
800 "resultCount": len(fallback_items),
801 })
802 return fallback_items, artifact
803
804
805 def _search_jobs(
806 company: str,
807 date_range: tuple[str, str],
808 config: dict[str, Any],
809 *,
810 web_backend: str,
811 explicit: bool,
812 site: str,
813 budget: LaneBudget,
814 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
815 attempted: list[str] = []
816
817 # --- A company whose board cannot be found from its site, or is not read. ---
818 registered = _registry_entry(site)
819 if registered is not None:
820 kind, entry = registered
821 if kind == "unreadable":
822 return _job_site_unreadable(
823 company, date_range, config, entry, entry["reason"],
824 attempted=attempted, web_backend=web_backend, explicit=explicit,
825 )
826 share = budget.step_deadline
827 attempted.append(f"company:{entry['provider']}:{entry['board']}")
828 hosted = entry["provider"] in _HOSTED_PROVIDERS
829 found, reason = _read_found_board(
830 company, entry["provider"], entry["board"], date_range,
831 attempted=attempted, explicit=explicit, budget=budget,
832 found_via="site", company_board=None if hosted else entry,
833 )
834 if found is not None:
835 return found
836 budget.step_deadline = share
837 if reason == "unanswered":
838 # A board that did not answer is not one that cannot be read:
839 # the budget names it, and a retry may read it. For a hosted
840 # board (e.g. Workday), the company's own site may still serve an
841 # owned job sitemap while the third-party host is slow/overloaded.
842 if hosted:
843 roster = _sitemap_tier(
844 company, date_range, _sitemap_hosts([], site),
845 attempted=attempted, explicit=explicit, budget=budget,
846 fallback=f"{entry['provider']} board did not answer",
847 )
848 if roster is not None:
849 return roster
850 return _web_tier(
851 company, date_range, config, attempted=attempted,
852 web_backend=web_backend, explicit=explicit,
853 )
854 return _fall_through(
855 company, date_range, config, entry, reason,
856 hosts=_sitemap_hosts([entry["board"]] if not hosted else [], site),
857 attempted=attempted, web_backend=web_backend, explicit=explicit, budget=budget,
858 )
859
860 # --- Discovery: fetch the careers page and read the board off it (Tier 1). ---
861 careers_html, careers_url, page_via = _find_careers_page(
862 company, date_range, config, backend=web_backend, site=site,
863 )
864 provider, slug = (None, None)
865 found_via = "slug-guess"
866 probed: list[dict[str, Any]] | None = None
867 # What the careers page calls its organization, when that is a longer or
868 # shorter form of the company's name ("Anduril Industries" for "Anduril").
869 # A page a web search named is anyone's page and is not read for this.
870 stated_names = [
871 name for name in _stated_names(careers_html or "")
872 if _leads_with(name, company) and not _same_company(name, company)
873 ] if page_via != "search" else []
874 platform: tuple[str, dict[str, Any]] | None = None
875 if careers_html:
876 provider, slug = detect_ats(careers_html)
877 if provider == PLATFORM_PROVIDER_KULA:
878 # A Kula board is under the slug the company chose, on Kula's own
879 # host, so a link from any careers page names it, as a hosted
880 # system's does; its platform reader reads it, and whose board it
881 # is follows from how the page was found or the name it states.
882 platform = (provider, board_detect.kula_entry(slug or ""))
883 provider = slug = None
884 elif provider:
885 attempted.append(f"careers:{provider}:{slug}")
886 found_via = page_via
887 elif page_via == "site":
888 # A hiring platform under the company's own host, named by the
889 # page: read by the platform's reader. Only on a site known to be
890 # the company's: a domain guessed from the name can be another
891 # business's, and a platform board states no company of its own
892 # (its reader names it after the company asked for), so it would
893 # pass as the company's. A page a web search named is not read
894 # for one either.
895 platform = board_detect.detect_platform(careers_html, careers_url or "")
896
897 if platform is not None:
898 share = budget.step_deadline
899 platform_provider, entry = platform
900 entry = {"name": company, **entry}
901 attempted.append(f"careers:{platform_provider}:{entry['board']}")
902 found, reason = _read_found_board(
903 company, platform_provider, entry["board"], date_range,
904 attempted=attempted, explicit=explicit, budget=budget,
905 found_via=page_via, company_board=entry,
906 )
907 if found is not None:
908 return found
909 budget.step_deadline = share
910 if reason == "unanswered":
911 return _web_tier(
912 company, date_range, config, attempted=attempted,
913 web_backend=web_backend, explicit=explicit,
914 )
915 sitemap_first = (
916 [entry["board"], _host(careers_url or "")]
917 if page_via == "site"
918 else []
919 )
920 return _fall_through(
921 company, date_range, config, {"name": company, "site": entry["board"]},
922 reason, hosts=_sitemap_hosts(sitemap_first, site),
923 attempted=attempted, web_backend=web_backend, explicit=explicit, budget=budget,
924 platform=platform_provider,
925 )
926
927 # Fallback discovery: cheap deterministic slug probe (only after careers-page
928 # discovery fails - never the entry point).
929 if not provider:
930 if stated_names:
931 provider, slug, probe_attempts, probed = _probe_boards(company, also=stated_names)
932 else:
933 provider, slug, probe_attempts, probed = _probe_boards(company)
934 attempted.extend(probe_attempts)
935 if provider and page_via == "site" and slug not in _candidate_slugs(company):
936 # The slug is the confirmed official site's own name for the
937 # company. A domain guessed from the company's name can be
938 # another business's, so the name it states may find a board but
939 # never makes it the company's: that board stays a slug guess.
940 found_via = "site-name"
941
942 # --- Tier 1: call the resolved ATS API. Trust it only if it has jobs. ---
943 # Finding the board may have had a share of the budget; reading a found
944 # board has all that is left. The share comes back when the board turns
945 # out to hold nothing, so the fallbacks below cannot spend the time of
946 # the companies still to be tried.
947 share = budget.step_deadline
948 if provider and slug:
949 found = _read_board(
950 company, provider, slug, date_range,
951 attempted=attempted, explicit=explicit, budget=budget,
952 found_via=found_via, probed=probed, stated_names=stated_names,
953 named_boards=_boards_named(careers_html or ""),
954 )
955 if found is not None:
956 return found
957
958 budget.step_deadline = share
959
960 # --- Tier 2: parse JSON-LD JobPosting off the careers page. ---
961 if careers_html:
962 attempted.append("careers:jsonld")
963 jsonld_items = extract_jsonld_jobs(careers_html, careers_url or "")
964 if jsonld_items:
965 return jsonld_items, _artifact("jobs", company, attempted, jsonld_items,
966 explicit, tier="careers-jsonld")
967
968 # --- The roster tier: the job sitemap of the company's own site. ---
969 if site and _host(site):
970 sitemap_first = [_host(careers_url or "")] if page_via == "site" else []
971 roster = _sitemap_tier(
972 company, date_range, _sitemap_hosts(sitemap_first, site),
973 attempted=attempted, explicit=explicit, budget=budget,
974 )
975 if roster is not None:
976 return roster
977
978 # --- Tier 3: generic web search (noisy, low-confidence). ---
979 return _web_tier(
980 company, date_range, config, attempted=attempted, web_backend=web_backend,
981 explicit=explicit,
982 )
983
984
985 # Providers ``_read_board`` reads by slug or token rather than through a
986 # company reader.
987 _HOSTED_PROVIDERS = frozenset({
988 ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER,
989 ATS_PROVIDER_WORKABLE, ATS_PROVIDER_SMARTRECRUITERS, ATS_PROVIDER_WORKDAY,
990 })
991 ROBOTS_REASON = "its robots.txt disallows the job listing"
992
993
994 def _read_found_board(
995 company: str,
996 provider: str,
997 board: str,
998 date_range: tuple[str, str],
999 *,
1000 attempted: list[str],
1001 explicit: bool,
1002 budget: LaneBudget,
1003 found_via: str,
1004 company_board: dict[str, Any] | None,
1005 ) -> tuple[tuple[list[dict[str, Any]], dict[str, Any]] | None, str]:
1006 """Read a board the registry or detection named; ``(found, reason)``.
1007
1008 ``reason`` says why nothing was read: ``unanswered`` for a board that did
1009 not answer (a retry may read it), or the words the footer gives.
1010 """
1011 entry = company_board or {"board": board}
1012 listing = _listing_url(provider, entry)
1013 if listing and board_robots.disallowed(
1014 listing, deadline_monotonic=time.monotonic() + max(0.0, budget.remaining()),
1015 ):
1016 attempted.append(f"robots-disallowed:{provider}:{board}")
1017 log.source_log(
1018 "Jobs", f"{company}: the {provider} board {board} is not read: {ROBOTS_REASON} "
1019 f"({board_robots.RESPECT_ROBOTS_VAR} is set)", tty_only=False,
1020 )
1021 return None, ROBOTS_REASON
1022 found = _read_board(
1023 company, provider, board, date_range,
1024 attempted=attempted, explicit=explicit, budget=budget,
1025 found_via=found_via, company_board=company_board,
1026 )
1027 if found is not None:
1028 return found, ""
1029 if budget.has_unanswered(f"the {provider} board {board} did not answer"):
1030 return None, "unanswered"
1031 return None, f"its {provider} board answered with an error or with no roles the lane could read"
1032
1033
1034 def _fall_through(
1035 company: str,
1036 date_range: tuple[str, str],
1037 config: dict[str, Any],
1038 entry: dict[str, str],
1039 reason: str,
1040 *,
1041 hosts: list[str],
1042 attempted: list[str],
1043 web_backend: str,
1044 explicit: bool,
1045 budget: LaneBudget,
1046 platform: str = "",
1047 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
1048 """A named board that could not be read: the site's job sitemap, then the
1049 web tier, and the run says which happened. Never a silent zero."""
1050 name = entry.get("name") or company
1051 roster = _sitemap_tier(
1052 company, date_range, hosts, attempted=attempted, explicit=explicit, budget=budget,
1053 fallback=f"{entry.get('provider') or platform or 'its'} board not read: {reason}",
1054 )
1055 if roster is not None:
1056 return roster
1057 return _job_site_unreadable(
1058 company, date_range, config, {**entry, "name": name}, reason,
1059 attempted=attempted, web_backend=web_backend, explicit=explicit,
1060 )
1061
1062
1063 def _is_shared_board_host(host: str) -> bool:
1064 """Whether ``host`` belongs to a shared multi-tenant ATS or hiring platform."""
1065 clean = _host(host)
1066 return bool(clean) and any(
1067 _same_site(clean, domain) for domain in _SHARED_PLATFORM_DOMAINS
1068 )
1069
1070
1071 def _is_owned_sitemap_host(host: str, site: str) -> bool:
1072 """Whether ``host`` is a company-dedicated host verified for ``site`` and
1073 safe to stamp as an owned job sitemap (never a multi-tenant platform)."""
1074 clean = _host(host)
1075 site_host = _host(site)
1076 if not clean or not site_host or _is_shared_board_host(clean):
1077 return False
1078 if _same_site(clean, site_host) or _named_jobs_host(clean, site):
1079 return True
1080 registered = _registry_entry(site)
1081 if registered is not None and registered[0] == "board":
1082 entry = registered[1]
1083 if entry.get("provider") not in _HOSTED_PROVIDERS and _same_site(
1084 clean, _host(entry.get("board", ""))
1085 ):
1086 return True
1087 hinted = next(
1088 (page for key, page in CAREERS_PAGES.items() if _same_site(site_host, key)),
1089 "",
1090 )
1091 return bool(hinted) and _same_site(clean, _host(hinted))
1092
1093
1094 def _sitemap_hosts(first: list[str], site: str) -> list[str]:
1095 """Hosts asked for a job sitemap: verified company-dedicated hosts first,
1096 then the official site's jobs and careers hosts, then the site itself.
1097
1098 Untrusted hosts and multi-tenant platform hosts are excluded because
1099 ``_sitemap_tier`` stamps the first matching host as ``owned=True``.
1100 """
1101 site_host = _host(site) if site else ""
1102 if not site_host:
1103 return []
1104 hosts = [
1105 host for host in first
1106 if host and _is_owned_sitemap_host(host, site)
1107 ]
1108 base = site_host.removeprefix("www.")
1109 if base:
1110 hosts += [
1111 candidate
1112 for candidate in (f"jobs.{base}", f"careers.{base}", site_host)
1113 if not _is_shared_board_host(candidate)
1114 ]
1115 return list(dict.fromkeys(host.lower() for host in hosts))
1116
1117
1118 def _sitemap_tier(
1119 company: str,
1120 date_range: tuple[str, str],
1121 hosts: list[str],
1122 *,
1123 attempted: list[str],
1124 explicit: bool,
1125 budget: LaneBudget,
1126 fallback: str = "",
1127 ) -> tuple[list[dict[str, Any]], dict[str, Any]] | None:
1128 """The roster tier (``lib.job_boards.sitemap``): roles listed in a job
1129 sitemap of the company's own site, as a board read titles only. None when
1130 no host has a job sitemap."""
1131 hosts = [host for host in hosts if not budget.is_unreachable(host)]
1132 if not hosts or _out_of_time("the job sitemap"):
1133 return None
1134 sitemap = importlib.import_module(f"{__package__}.job_boards.sitemap")
1135 deadline = min(budget.deadline, budget.step_deadline) - budget.remaining() * DETAIL_SHARE
1136 attempted.append("sitemap:" + ",".join(hosts[:4]))
1137 def read() -> tuple[list[dict[str, Any]], dict[str, Any]]:
1138 try:
1139 return sitemap.read_roster(hosts, company=company, deadline=deadline)
1140 except (UnicodeDecodeError, ValueError):
1141 # A sitemap that is not text, or not XML a pattern can read.
1142 return [], {}
1143
1144 items, info = _within_budget(read, "the job sitemap", ([], {}))
1145 total = int(info.get("board_total") or 0)
1146 if not total:
1147 return None
1148 host = str(info.get("board_sitemap_host") or "")
1149 artifact = _artifact("jobs", company, attempted, items, explicit,
1150 tier="ats", provider=SITEMAP_PROVIDER, slug=host)
1151 artifact.update(info)
1152 artifact.update({
1153 "found_via": "site", "board_company": company, "owned": True,
1154 "titles_only": True,
1155 "open_roles": total, "open_roles_floor": bool(info.get("board_total_floor")),
1156 "new_in_window": None,
1157 })
1158 if fallback:
1159 artifact["board_fallback"] = fallback
1160 notes = []
1161 if fallback:
1162 notes.append(fallback)
1163 story_record = _local_story_record(items)
1164 if story_record is not None:
1165 artifact["story_search"] = story_record
1166 if items:
1167 eligible = [item for item in items if not item.get("digest_excluded")]
1168 teams = jobs_teams.named_teams(eligible, company=company, window_start=date_range[0])
1169 selected = jobs_digest.select_roles(eligible, open_roles=total, teams=teams)
1170 artifact["digest"] = jobs_digest.build_digest(eligible, selected)
1171 artifact["digest"]["teams"] = teams["teams"]
1172 artifact["digest"]["titles_only"] = True
1173 notes.append(
1174 f"titles only: the roles come from the job sitemap of {host}, "
1175 "whose role pages could not be read, so each role is its title and link"
1176 + (f" ({len(items):,} of {total:,} listed roles have a title)"
1177 if len(items) < total else "")
1178 )
1179 artifact["digest"]["note"] = "; ".join(notes)
1180 else:
1181 notes.append(
1182 f"{total:,} roles are listed in the job sitemap of {host}, "
1183 "but neither their addresses nor their pages give a title"
1184 )
1185 artifact["coverage_note"] = "; ".join(notes)
1186 log.source_log("Jobs", f"{company}: {artifact['coverage_note']}", tty_only=False)
1187 return items, artifact
1188
1189
1190 def _read_board(
1191 company: str,
1192 provider: str,
1193 slug: str,
1194 date_range: tuple[str, str],
1195 *,
1196 attempted: list[str],
1197 explicit: bool,
1198 budget: LaneBudget,
1199 found_via: str,
1200 probed: list[dict[str, Any]] | None = None,
1201 stated_names: list[str] | None = None,
1202 owner: Callable[[str], tuple[str, str]] | None = None,
1203 full: bool = True,
1204 probed_board: dict[str, Any] | None = None,
1205 company_board: dict[str, str] | None = None,
1206 named_boards: set[tuple[str, str]] | frozenset[tuple[str, str]] = frozenset(),
1207 ) -> tuple[list[dict[str, Any]], dict[str, Any]] | None:
1208 """Read a found board and build its artifact, or None when it holds nothing.
1209
1210 A board belongs to the company when its known official site links to it
1211 or the board names the company. A guessed slug or a guessed domain can be
1212 another company's, so such a board still counts roles but gives no digest
1213 unless it names the company. A board under a slug taken from the name the
1214 company's confirmed official site states (``site-name``) is the company's
1215 when the board states that same name.
1216
1217 ``owner`` decides instead for a board the host passed: given the name the
1218 board states, it returns the company whose board it is (or '') and how
1219 that is known. With ``full`` off (a host board not yet tied to the
1220 company) the read stays inside the discovery share and a paged board
1221 gives its first page only.
1222
1223 ``company_board`` is the registry entry of a company-run board, which is
1224 read by its own reader. Its listing stops early enough to leave
1225 ``DETAIL_SHARE`` of the time for the role text of the selected roles.
1226
1227 A Workday board that is the company's is read with every other career
1228 site of its tenant: those its host's robots.txt lists and those of
1229 ``named_boards`` (the boards the careers page names) on the same tenant.
1230 """
1231 if full:
1232 budget.limit_discovery(None)
1233 board: dict[str, Any] = dict(probed_board or {})
1234 deadline = budget.deadline if full else min(budget.deadline, budget.step_deadline)
1235 list_deadline = deadline
1236 if company_board is not None and provider in _DETAIL_FETCHERS:
1237 list_deadline = deadline - budget.remaining() * DETAIL_SHARE
1238 # Passed only when set, so the plain call stays what it always was.
1239 part: dict[str, Any] = {} if full else {"first_page_only": True}
1240 tenant_sites: list[str] = []
1241 # Rows the board's own search found for the run's story terms, and what
1242 # that search did; asked before the newest-first read, on a board read
1243 # in full.
1244 story_rows: list[dict[str, Any]] = []
1245 story_record: dict[str, Any] | None = None
1246 try:
1247 if probed is not None:
1248 # The probe already read this board; it is not read twice.
1249 items = probed
1250 elif _out_of_time(f"reading the {provider} board {slug}"):
1251 items = []
1252 elif company_board is not None:
1253 if full:
1254 story_rows, story_record = _search_story(provider, [company_board])
1255 if story_record is not None and provider in _DETAIL_FETCHERS:
1256 list_deadline = deadline - budget.remaining() * DETAIL_SHARE
1257 items, board = _company_reader(provider)(
1258 company_board, deadline=list_deadline, date_range=date_range,
1259 )
1260 elif provider == ATS_PROVIDER_WORKDAY:
1261 if full:
1262 # Asked before the listing pages: a tenant answers a burst of
1263 # them with 429 to every request for a while after.
1264 tenant_sites = workday_tenant_sites(
1265 slug, named_boards,
1266 deadline_monotonic=time.monotonic() + max(0.0, budget.remaining()),
1267 )
1268 # Every site of the tenant is one company's, under one cap.
1269 story_rows, story_record = _search_story(provider, [slug, *tenant_sites])
1270 items, board = search_workday_board(slug, deadline=deadline, **part)
1271 elif provider == ATS_PROVIDER_SMARTRECRUITERS:
1272 items, board = read_smartrecruiters_board(slug, deadline=deadline, **part)
1273 elif provider == ATS_PROVIDER_WORKABLE:
1274 items, board = read_workable_board(slug)
1275 else:
1276 items = _fetch_ats(provider, slug)
1277 except http.HTTPError as exc:
1278 if exc.outcome_state == health.TIMEOUT:
1279 _note_slow(f"the {provider} board {slug} did not answer")
1280 # Its own request limit or the lane's: either way the board
1281 # was found and not read, which is said by name.
1282 budget.note_unanswered(f"the {provider} board {slug} did not answer")
1283 items = []
1284 except ValueError as exc: # BoardShapeError, UnicodeDecodeError, bad JSON
1285 # A company reader's answer in a shape or encoding it cannot read:
1286 # the board was not read, and the run falls through, not over.
1287 if company_board is None:
1288 raise
1289 log.source_log(
1290 "Jobs", f"{company}: the {provider} board {slug} could not be read "
1291 f"({type(exc).__name__})", tty_only=False,
1292 )
1293 items = []
1294 if not items:
1295 if board.get("board_unanswered"):
1296 _note_slow(f"the {provider} board {slug} did not answer")
1297 budget.note_unanswered(f"the {provider} board {slug} did not answer")
1298 return None
1299 stated = next(
1300 (str(item["company_name"]) for item in items if item.get("company_name")), "",
1301 )
1302 if owner is not None:
1303 owned_by, found_via = owner(stated)
1304 owned = bool(owned_by)
1305 company = owned_by or company
1306 else:
1307 owned = (
1308 found_via == "site"
1309 or _same_company(stated, company)
1310 or (
1311 found_via == "site-name"
1312 and any(_same_company(stated, name) for name in stated_names or [])
1313 )
1314 )
1315 if owned and tenant_sites:
1316 # The tenant's other career sites are the company's too. They leave
1317 # the role text of the selected roles its share of the time.
1318 items, board = read_workday_tenant_sites(
1319 slug, items, board, tenant_sites,
1320 deadline=deadline - budget.remaining() * DETAIL_SHARE,
1321 )
1322 artifact = _artifact("jobs", company, attempted, items, explicit,
1323 tier="ats", provider=provider, slug=slug)
1324 artifact.update(board)
1325 artifact.update({
1326 "found_via": found_via,
1327 "board_company": stated,
1328 "owned": owned,
1329 })
1330 extras: list[dict[str, Any]] = []
1331 if owned:
1332 if provider in _STORY_LOCAL:
1333 story_record = _local_story_record(items)
1334 elif story_record is not None:
1335 extras = _merge_story_rows(items, story_rows)
1336 story_record["matches"] = _story_matches([*items, *extras])
1337 elif _story_terms():
1338 # A board this lane has no story search for, or read in part.
1339 story_record = _story_record(ran=False, terms=[])
1340 if story_record is not None:
1341 artifact["story_search"] = story_record
1342 # Roles a board marks as kept out of the digest (Apple's retail store
1343 # roles) are counted on the board but never chosen.
1344 eligible = [item for item in items if not item.get("digest_excluded")]
1345 # Story matches the newest-first read did not reach may be chosen,
1346 # and are never counted as the board's roles.
1347 # Named teams are read from the board's own roles, never story extras.
1348 teams = jobs_teams.named_teams(eligible, company=company, window_start=date_range[0])
1349 selected = jobs_digest.select_roles(
1350 eligible + [item for item in extras if not item.get("digest_excluded")],
1351 open_roles=_board_counts(items, board, date_range)["open_roles"],
1352 teams=teams,
1353 )
1354 late = failed = 0
1355 fetch_details = _detail_fetcher(provider)
1356 if fetch_details is not None:
1357 late, failed = fetch_details(
1358 [role["item"] for role in selected], deadline=deadline,
1359 )
1360 artifact["digest"] = jobs_digest.build_digest(eligible, selected)
1361 artifact["digest"]["teams"] = teams["teams"]
1362 notes = []
1363 coverage = _coverage_note(items, board, provider, budget)
1364 if coverage:
1365 notes.append(f"{coverage}, so the roles below are chosen from the rows read")
1366 if late or failed:
1367 reasons = []
1368 if late:
1369 reasons.append(f"time budget spent before {late}")
1370 if failed:
1371 reasons.append(f"request failed or came back empty for {failed}")
1372 notes.append(
1373 f"role text fetched for {len(selected) - late - failed} of "
1374 f"{len(selected)} selected roles ({'; '.join(reasons)})"
1375 )
1376 if notes:
1377 artifact["digest"]["note"] = "; ".join(notes)
1378 # Counted last: Workday's true posted dates arrive with the detail
1379 # calls above.
1380 artifact.update(_board_counts(items, board, date_range))
1381 coverage = _coverage_note(items, board, provider, budget)
1382 if coverage:
1383 artifact["coverage_note"] = coverage
1384 log.source_log(
1385 "Jobs", f"{company}: {provider} board {slug}: {coverage}", tty_only=False,
1386 )
1387 return items, artifact
1388
1389
1390 def parse_board_url(url: str) -> tuple[str | None, str | None]:
1391 """The provider and slug of a job-board URL, or ``(None, None)``.
1392
1393 Only a URL whose host is one of the supported systems' own is read, so a
1394 system's name in the path or query of another site is not a board.
1395 """
1396 text = (url or "").strip()
1397 if not text or "\\" in text or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text):
1398 return None, None
1399 try:
1400 parsed = urlparse(text if "://" in text else f"https://{text}")
1401 port = parsed.port
1402 except ValueError:
1403 return None, None
1404 scheme = parsed.scheme.lower()
1405 if scheme not in ("http", "https"):
1406 return None, None
1407 if parsed.username is not None or parsed.password is not None:
1408 return None, None
1409 if port is not None and not (
1410 (scheme == "https" and port == 443) or (scheme == "http" and port == 80)
1411 ):
1412 return None, None
1413 host = (parsed.hostname or "").rstrip(".").lower().removeprefix("www.")
1414 if not host or not any(_same_site(host, domain) for domain in _BOARD_DOMAINS):
1415 return None, None
1416 return detect_ats(host + parsed.path + (f"?{parsed.query}" if parsed.query else ""))
1417
1418
1419 def search_board_url(
1420 url: str,
1421 companies: list[str],
1422 date_range: tuple[str, str],
1423 config: dict[str, Any],
1424 *,
1425 site: str = "",
1426 sites: dict[str, str] | None = None,
1427 explicit: bool = False,
1428 budget: LaneBudget | None = None,
1429 discovery_seconds: float | None = None,
1430 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
1431 """Read the board at a URL the host found by web search (``--jobs-board``).
1432
1433 ``companies`` are the names the board may belong to: the topic or the
1434 company it resolved to, then the companies the host named. The board is
1435 one of theirs when the name it states is that company's (or leads with
1436 it as whole words: "Anduril Industries" for "Anduril"), when it states no
1437 name and its slug is the company's name, or when the official ``site``
1438 links to it (``site`` is the first company's; ``sites`` gives the
1439 confirmed site of any other by name). Any other board gives its counts
1440 and no digest, with a line on stderr saying why. A URL that is not on a
1441 supported system, or a board that cannot be read, gives ``([], {})`` and
1442 one line.
1443
1444 Whose board it is is settled before the board is read in full. Until
1445 then the call stays inside ``discovery_seconds``, its share of the
1446 budget, and a paged board (Workday, SmartRecruiters) that is not the
1447 company's gives its first page only, so a large board passed by mistake
1448 leaves the lane time to find the right one.
1449 """
1450 companies = [name.strip() for name in companies if name and name.strip()]
1451 provider, slug = parse_board_url(url)
1452 if not provider or not slug:
1453 log.source_log(
1454 "Jobs",
1455 f"--jobs-board ignored: {_host(url) or url.strip()[:80] or 'the value'} is not a "
1456 f"job board the lane reads ({SUPPORTED_SYSTEMS})",
1457 tty_only=False,
1458 )
1459 return [], {}
1460 if not companies:
1461 return [], {}
1462 budget = budget or LaneBudget()
1463 budget.limit_discovery(discovery_seconds)
1464 token = _BUDGET.set(budget)
1465 story_token = _STORY.set(_story_search_for(config))
1466 known_sites = {companies[0]: site, **(sites or {})}
1467
1468 def owner(stated: str) -> tuple[str, str]:
1469 # A board that states no name is known by its slug (Workday: its tenant).
1470 own = stated or slug.split(".", 1)[0]
1471 for name in companies:
1472 if _same_company(own, name) or (stated and _leads_with(stated, name)):
1473 return name, "host"
1474 checked_site = False
1475 for name in companies:
1476 if not known_sites.get(name):
1477 continue
1478 checked_site = True
1479 if _site_links_board(name, known_sites[name], provider, slug, date_range, config):
1480 return name, "site"
1481 named = f"names {stated!r}" if stated else "states no company name"
1482 checked = (
1483 "and the official site does not link it" if checked_site
1484 else "and there is no official site to check it against"
1485 )
1486 log.source_log(
1487 "Jobs",
1488 f"--jobs-board: the {provider} board {slug} {named}, not "
1489 f"{' or '.join(companies)}, {checked}; its roles are counted, with no digest",
1490 tty_only=False,
1491 )
1492 return "", "host"
1493
1494 try:
1495 # A board that is not there is the host's wrong URL, not an outage.
1496 with http.expected_misses(400, 401, 403, 404):
1497 # Whose board it is can be known before the board is read: most
1498 # systems state no name, Greenhouse states it in the board's own
1499 # record, and SmartRecruiters on every row of its first page.
1500 settled: tuple[str, str] | None = None
1501 first: list[dict[str, Any]] | None = None
1502 _info: dict[str, Any] = {}
1503 if provider == ATS_PROVIDER_GREENHOUSE:
1504 stated = _greenhouse_board_name(slug)
1505 # With no record to go by, the rows say whose it is.
1506 settled = owner(stated) if stated else None
1507 elif provider != ATS_PROVIDER_SMARTRECRUITERS:
1508 settled = owner("")
1509 else:
1510 first, _info = read_smartrecruiters_board(
1511 slug, deadline=min(budget.deadline, budget.step_deadline),
1512 first_page_only=True,
1513 )
1514 settled = owner(next(
1515 (str(item["company_name"]) for item in first if item.get("company_name")), "",
1516 )) if first else ("", "host")
1517 # A board that is not the company's is not read past the page
1518 # that showed whose it is.
1519 unowned_page = first if settled is not None and not settled[0] else None
1520 found = _read_board(
1521 companies[0], provider, slug, date_range,
1522 attempted=[f"host:{provider}:{slug}"], explicit=explicit, budget=budget,
1523 found_via="host",
1524 owner=(lambda _stated: settled) if settled is not None else owner,
1525 # Only a board already known to be the company's leaves the
1526 # share and is read with all the time the lane has left.
1527 full=bool(settled and settled[0]),
1528 probed=unowned_page, probed_board=_info if unowned_page else None,
1529 )
1530 except http.HTTPError:
1531 found = None
1532 finally:
1533 _STORY.reset(story_token)
1534 _BUDGET.reset(token)
1535 budget.limit_discovery(None)
1536 if found is None:
1537 log.source_log(
1538 "Jobs",
1539 f"--jobs-board: the {provider} board {slug} could not be read or lists no "
1540 "roles; looking for the company's board without it",
1541 tty_only=False,
1542 )
1543 return [], {}
1544 return found
1545
1546
1547 def _greenhouse_board_name(slug: str) -> str:
1548 """The company name a Greenhouse board's own record states, or '' when
1549 the record could not be read. One small request, where the board's job
1550 list can be megabytes."""
1551 try:
1552 data = http.get(
1553 f"https://boards-api.greenhouse.io/v1/boards/{slug}",
1554 retries=1, **_bounds(API_TIMEOUT_SECONDS),
1555 )
1556 except http.HTTPError:
1557 return ""
1558 return " ".join(str(data.get("name") or "").split()) if isinstance(data, dict) else ""
1559
1560
1561 def _site_links_board(
1562 company: str,
1563 site: str,
1564 provider: str,
1565 slug: str,
1566 date_range: tuple[str, str],
1567 config: dict[str, Any],
1568 ) -> bool:
1569 """Whether the official site's careers page, or the jobs page it links
1570 to, names this board."""
1571 html, _url = _resolve_careers_page(company, date_range, config, backend="none", site=site)
1572 return (provider, slug.lower()) in _boards_named(html or "")
1573
1574
1575 def _boards_named(html: str) -> set[tuple[str, str]]:
1576 """Every (provider, lower-cased slug) a page names."""
1577 bounded = (html or "")[:board_detect.MAX_HTML_CHARS]
1578 named: set[tuple[str, str]] = set()
1579 for provider, pattern in _ATS_LINK_PATTERNS:
1580 for match in re.finditer(pattern, bounded):
1581 slug = match.group(match.lastindex or 1).strip().strip("/.")
1582 if not slug or slug.lower() in _SLUG_STOPWORDS:
1583 continue
1584 if provider == ATS_PROVIDER_WORKDAY:
1585 slug = f"{match.group(1)}.{match.group(2)}/{slug}"
1586 named.add((provider, slug.lower()))
1587 return named
1588
1589
1590 _ORGANIZATION_TYPES = {"organization", "corporation", "localbusiness"}
1591 _STATED_NAME_LIMIT = 3
1592
1593
1594 def extract_jsonld_blocks(html: str) -> list[str]:
1595 """Extract raw JSON-LD ``<script type="application/ld+json">`` blocks in linear time."""
1596 return board_detect.extract_jsonld_blocks(html)
1597
1598
1599 def _stated_names(html: str) -> list[str]:
1600 """What a page calls the organization behind it: the names of the
1601 Organization in its structured data, then its ``og:site_name``."""
1602 names: list[str] = []
1603
1604 def add(value: Any, *, unescape_entities: bool = True) -> None:
1605 for name in value if isinstance(value, list) else [value]:
1606 if not isinstance(name, str):
1607 continue
1608 raw = unescape(name) if unescape_entities else name
1609 text = " ".join(raw.split())
1610 if text and len(text) <= 80 and text not in names:
1611 names.append(text)
1612
1613 def walk(node: Any, depth: int = 0) -> None:
1614 if depth > 8:
1615 return
1616 if isinstance(node, list):
1617 for child in node:
1618 walk(child, depth + 1)
1619 elif isinstance(node, dict):
1620 kinds = node.get("@type")
1621 kinds = kinds if isinstance(kinds, list) else [kinds]
1622 if any(isinstance(kind, str) and kind.lower() in _ORGANIZATION_TYPES for kind in kinds):
1623 for key in ("name", "legalName", "alternateName"):
1624 add(node.get(key))
1625 for child in node.values():
1626 if isinstance(child, (dict, list)):
1627 walk(child, depth + 1)
1628
1629 for block in extract_jsonld_blocks(html or ""):
1630 try:
1631 walk(json.loads(block.strip()))
1632 except (json.JSONDecodeError, ValueError, RecursionError):
1633 continue
1634 add(
1635 board_detect.extract_meta_contents(html or "", "property", "og:site_name"),
1636 unescape_entities=False,
1637 )
1638 return names[:_STATED_NAME_LIMIT]
1639
1640
1641 # --------------------------------------------------------------------------- #
1642 # Careers-page discovery
1643 # --------------------------------------------------------------------------- #
1644
1645 def _coverage_note(
1646 items: list[dict[str, Any]], board: dict[str, Any], provider: str, budget: LaneBudget,
1647 ) -> str:
1648 """What stopped a board's listing short of the rows it reports, or ''."""
1649 if not board.get("board_cut_short"):
1650 return ""
1651 listed = int(board.get("board_total") or 0)
1652 if not (board.get("board_newest_first") or board.get("board_reports_total")):
1653 listed = min(listed, int(board.get("board_row_ceiling") or WORKDAY_ROW_CEILING))
1654 rows = int(board.get("board_rows_read") or len(items))
1655 read = f"{rows:,} rows read" + (
1656 f" of the {listed:,} the board lists" if listed > rows else ""
1657 )
1658 if board.get("board_newest_first") or board.get("board_reports_total"):
1659 cause = (
1660 "the newest roles are read first" if board.get("board_newest_first")
1661 else "the board is read in its own order, which is not by date"
1662 )
1663 if budget.spent():
1664 cause += f" and the lane's {budget.seconds:g}s time budget ran out"
1665 elif board.get("board_row_ceiling"):
1666 cause += f", up to {int(board['board_row_ceiling']):,} rows"
1667 elif provider == ATS_PROVIDER_WORKABLE:
1668 cause = "only the board's first page is read"
1669 elif board.get("board_first_page_only"):
1670 cause = "only the first page of a board not tied to the company is read"
1671 elif budget.spent():
1672 cause = f"the lane's {budget.seconds:g}s time budget ran out"
1673 else:
1674 cause = "a listing page failed or the board gave no total"
1675 return f"board read in part: {read} ({cause})"
1676
1677
1678 def _resolve_careers_page(
1679 company: str,
1680 date_range: tuple[str, str],
1681 config: dict[str, Any],
1682 *,
1683 backend: str = "auto",
1684 site: str = "",
1685 ) -> tuple[str | None, str | None]:
1686 """Find and fetch the company's careers page HTML: ``(html, url)`` or
1687 ``(None, None)``. See ``_find_careers_page``."""
1688 html, url, _via = _find_careers_page(company, date_range, config, backend=backend, site=site)
1689 return html, url
1690
1691
1692 def _find_careers_page(
1693 company: str,
1694 date_range: tuple[str, str],
1695 config: dict[str, Any],
1696 *,
1697 backend: str = "auto",
1698 site: str = "",
1699 ) -> tuple[str | None, str | None, str]:
1700 """Find and fetch the company's careers page HTML.
1701
1702 Tries conventional URLs on the company's known site, or on guessed
1703 domains when no site is known (free, deterministic). On a known site it
1704 also tries the site's ``careers.`` and ``jobs.`` hosts, which is where a
1705 large company's careers site often answers when its main site blocks
1706 automated requests, and a careers page the registry names for it
1707 (``CAREERS_PAGES``). A page that names a board ends the search; otherwise
1708 the first careers page found is kept. Falls back to a single web search
1709 for the careers page when a backend is configured.
1710
1711 Returns ``(html, url, via)``: ``url`` is the address that answered (after
1712 redirects), so a platform under the company's own host is called there,
1713 and ``via`` is how the page was reached (``site``, ``guess`` or
1714 ``search``, as ``_found_via`` says). Never raises.
1715 """
1716 # Only a host guessed from the company's name may turn out not to exist.
1717 guessed = not (site and _host(site))
1718 kept: tuple[str, str, str] | None = None
1719 # Hosts that gave no answer at all: their other page is not asked.
1720 dead: set[str] = set()
1721 budget = _BUDGET.get()
1722 for phase in _careers_candidates(company, site):
1723 # The site answered on its other host form: ask that one from now on.
1724 moved: dict[str, str] = {}
1725 for url, on_site, named in phase:
1726 host = _host(url)
1727 if host in moved:
1728 url = url.replace(f"//{host}", f"//{moved[host]}", 1)
1729 host = moved[host]
1730 if host in dead:
1731 continue
1732 if _out_of_time(f"the careers page {url}"):
1733 return kept or (None, None, "search")
1734 page, no_answer, used = _careers_page_at(
1735 url, guessed=guessed or not on_site, company=company, site=site, named=named,
1736 )
1737 if _host(used) != host:
1738 moved[host] = _host(used)
1739 if no_answer:
1740 dead.add(host)
1741 if budget is not None:
1742 # Both host forms were asked for a known site.
1743 budget.mark_unreachable({host, f"www.{host.removeprefix('www.')}",
1744 host.removeprefix("www.")})
1745 if page is None:
1746 continue
1747 if _names_board(page[0], page[1]):
1748 return page
1749 if kept is None:
1750 kept = page
1751 # The site's first careers page ends this group of pages; a
1752 # later group is tried only while no page has named a board.
1753 break
1754 if kept is not None:
1755 return kept
1756
1757 if backend != "none":
1758 careers_url = _within_budget(
1759 lambda: _search_for_careers_url(company, date_range, config, backend=backend),
1760 "the web search for the careers page",
1761 None,
1762 )
1763 if careers_url and not _out_of_time(f"the careers page {careers_url}"):
1764 # A page a web search named, on anyone's host: like a guessed
1765 # domain, its failure to answer is not an outage of the lane.
1766 html, _no_answer = _careers_text(careers_url, guessed=True)
1767 if html:
1768 budget = _BUDGET.get()
1769 landed = (budget.get_landed(careers_url) if budget is not None else None) or careers_url
1770 if board_detect.is_safe_public_url(landed) and (
1771 _same_site(_host(landed), _host(careers_url)) or _jobs_host(_host(landed))
1772 ):
1773 return html, landed, _found_via(landed, company, site)
1774
1775 return None, None, "search"
1776
1777
1778 def _careers_candidates(company: str, site: str) -> list[list[tuple[str, bool, bool]]]:
1779 """Careers page URLs to try, in groups, each with whether it is on the
1780 host the run knows or guessed, and whether the registry names it as the
1781 known site's careers page.
1782
1783 The groups: a careers page the registry names (``CAREERS_PAGES``); the
1784 ``/careers`` and ``/jobs`` pages of the known site, or of each guessed
1785 domain; then, for a known site only, its ``careers.`` and ``jobs.`` hosts,
1786 which may not exist.
1787 """
1788 groups: list[list[tuple[str, bool, bool]]] = []
1789 known = bool(site and _host(site))
1790 if known:
1791 hinted = next(
1792 (page for key, page in CAREERS_PAGES.items() if _same_site(_host(site), key)), "",
1793 )
1794 if hinted:
1795 groups.append([(hinted, False, True)])
1796 for host in _site_hosts(company, site):
1797 registered = _registry_entry(host)
1798 if registered is not None and registered[0] == "unreadable":
1799 # A job site the lane does not read gets no request, on any path.
1800 continue
1801 groups.append([(f"https://{host}{path}", True, False) for path in ("/careers", "/jobs")])
1802 if known:
1803 base = _host(site).removeprefix("www.")
1804 groups.extend([(f"https://{label}.{base}/", False, False)] for label in ("careers", "jobs"))
1805 return groups
1806
1807
1808 def _careers_page_at(
1809 url: str, *, guessed: bool, company: str, site: str, named: bool = False,
1810 ) -> tuple[tuple[str, str, str] | None, bool, str]:
1811 """The careers page at ``url`` and the page naming its board, if any,
1812 whether the host gave no answer at all, and the URL that was asked (the
1813 site's other host form when that is the one that answered).
1814
1815 The page is ``(html, landed, via)``. A guessed URL (a domain guessed from
1816 the name, a ``careers.``/``jobs.`` host of the known site, a registry
1817 careers page) may not exist, so its failure is recorded nowhere. A page
1818 that redirected off the company's site to a host that is not a jobs or
1819 careers host (``microsoft.com/careers`` to a search engine) is not its
1820 careers page. A page the registry names for the known site (``named``)
1821 is the site's own, wherever it is hosted.
1822 """
1823 budget = _BUDGET.get()
1824 if guessed:
1825 html, no_answer = _careers_text(url, guessed=True)
1826 else:
1827 html, no_answer, url = _known_site_text(url)
1828 if not html:
1829 return None, no_answer, url
1830 landed = (budget.get_landed(url) if budget is not None else None) or url
1831 if not board_detect.is_safe_public_url(landed):
1832 return None, False, url
1833 if not (_same_site(_host(landed), _host(url)) or _jobs_host(_host(landed)) or named):
1834 return None, False, url
1835 if not (_looks_like_careers_html(html) or _names_board(html, landed)):
1836 return None, False, url
1837 page, page_url = _board_page(html, landed, guessed=guessed)
1838 return (page, page_url, "site" if named else _found_via(landed, company, site)), False, url
1839
1840
1841 def _names_board(html: str, url: str) -> bool:
1842 """Whether a page names a board the lane reads: a hosted system's link or
1843 a hiring platform's markup."""
1844 return bool(detect_ats(html)[0] or board_detect.detect_platform(html, url))
1845
1846
1847 def _jobs_host(host: str) -> bool:
1848 """A host whose name says it serves jobs (``jobs.``, ``careers.``,
1849 ``apply.careers.``, ``explore.jobs.``)."""
1850 return bool(re.search(r"(?:^|\.)(?:jobs|careers?)\.", host or ""))
1851
1852
1853 def _known_site_text(url: str) -> tuple[str | None, bool, str]:
1854 """A page on the company's known site, retried once on the site's other
1855 host form (``www.`` or bare) when the connection was dropped. Returns the
1856 page text, whether the host gave no answer (counting both forms dropping
1857 the connection), and the URL that was read."""
1858 answers: dict[str, tuple[str | None, bool]] = {}
1859
1860 def fetch(page: str) -> str | None:
1861 with http.tee_failures() as failures:
1862 text, gone = _careers_text(page, guessed=False)
1863 answers[page] = (text, gone or http.connection_dropped(failures))
1864 return text
1865
1866 html, used = http.text_on_either_host_form(fetch, url)
1867 if html is None:
1868 # A form that answered, even with a 403 or 404, is where the site's
1869 # other page is asked.
1870 used = next((page for page, (_text, gone) in answers.items() if not gone), used)
1871 # Only when every form tried gave no answer is the other page not asked.
1872 return html, all(gone for _text, gone in answers.values()), used
1873
1874
1875 def _careers_text(url: str, *, guessed: bool) -> tuple[str | None, bool]:
1876 """Fetch a careers page on the company's site or on a guessed domain.
1877
1878 Returns the page text, and whether the host gave no answer at all: its
1879 name did not resolve, it refused the connection, or it did not answer in
1880 time. A 403 or 404 is a page that is not there, never a run failure. On a
1881 ``guessed`` domain no answer means the company has no such site: no board
1882 was found, so nothing is recorded as a failure, and a host that only
1883 timed out is named in the budget's ``slow`` list. On the known official
1884 site the same failure is an outage and is recorded.
1885
1886 One attempt, no longer than ``GUESS_TIMEOUT_SECONDS`` on a guessed domain
1887 or ``PAGE_TIMEOUT_SECONDS`` on the official site, and never past the
1888 lane's budget.
1889 """
1890 host = _host(url)
1891 try:
1892 return _careers_fetch(url, host, guessed=guessed)
1893 except UnicodeDecodeError:
1894 # Not a text page (a file, or text in another encoding): no page.
1895 return None, False
1896
1897
1898 def _careers_fetch(url: str, host: str, *, guessed: bool) -> tuple[str | None, bool]:
1899 if not board_detect.is_safe_public_url(url):
1900 return None, False
1901 guard = board_detect.public_redirect_guard(url)
1902 landed: list[str] = []
1903 budget = _BUDGET.get()
1904 with http.expected_misses(403, 404):
1905 if guessed:
1906 # ``capture_failures`` keeps a guessed host's failures out of the
1907 # run's record, whatever they are.
1908 with http.capture_failures() as failures:
1909 html = http.get_text(
1910 url, accept="text/html", retries=1, retry_dns=False, landed=landed,
1911 public_only=True, redirect_guard=guard,
1912 max_bytes=board_detect.MAX_HTML_BYTES, **_bounds(GUESS_TIMEOUT_SECONDS),
1913 )
1914 if any(failure.outcome_state == health.TIMEOUT for failure in failures):
1915 _note_slow(f"{host} did not answer in {GUESS_TIMEOUT_SECONDS}s")
1916 if landed and budget is not None:
1917 budget.record_landed(url, landed[-1])
1918 return html, any(failure.status_code is None for failure in failures)
1919 with http.tee_failures() as failures:
1920 html = http.get_text(
1921 url, accept="text/html", retries=1, landed=landed, public_only=True,
1922 redirect_guard=guard,
1923 max_bytes=board_detect.MAX_HTML_BYTES, **_bounds(PAGE_TIMEOUT_SECONDS),
1924 )
1925 if landed and budget is not None:
1926 budget.record_landed(url, landed[-1])
1927 timed_out = any(failure.outcome_state == health.TIMEOUT for failure in failures)
1928 if timed_out:
1929 _note_slow(f"{host} did not answer in {PAGE_TIMEOUT_SECONDS}s")
1930 return html, timed_out or any(failure.no_host for failure in failures)
1931
1932
1933 # How many pages linked from a careers page are read when looking for the board.
1934 _LINKED_PAGE_LIMIT = 2
1935 _JOBS_LINK_WORDS = re.compile(r"job|position|opening|vacanc|search|board|role", re.I)
1936 # A link to a file is not a jobs page (a PDF under /jobs/ is a legal notice).
1937 _FILE_LINK = re.compile(r"\.(?:pdf|docx?|xlsx?|pptx?|zip|png|jpe?g|gif|svg|webp|mp4|ics|xml|json|css|js)$", re.I)
1938 _GENERIC_HOST_LABELS = board_detect._SECOND_LEVEL_PUBLIC_LABELS | frozenset({
1939 "www", "jobs", "career", "careers", "int",
1940 })
1941
1942
1943 def _board_page(html: str, url: str, *, guessed: bool = False) -> tuple[str, str]:
1944 """The page that names the company's board: the careers page, or a jobs
1945 page it links to.
1946
1947 A large company's careers page is often a landing page whose job search
1948 lives one link away, on a host of its own (``jobs.nvidia.com``), and only
1949 that page names the hiring system. Up to ``_LINKED_PAGE_LIMIT`` such links
1950 are followed: within the careers page's own site, or to a jobs host that
1951 carries the site's name (``explore.jobs.netflix.net`` from
1952 ``jobs.netflix.com``), so a board found this way is named by the page
1953 the company's site led to. An Eightfold board the page points at by name
1954 (``careers-eightFoldCareerUrl``) is followed first.
1955
1956 Returns the page and the address that answered with it.
1957 """
1958 if _names_board(html, url):
1959 return html, url
1960 budget = _BUDGET.get()
1961 pointed = board_detect.eightfold_career_url(html)
1962 links = _jobs_links(html, url)
1963 if pointed and board_detect.is_safe_public_url(pointed) and (
1964 _same_site(_host(pointed), _host(url)) or _named_jobs_host(_host(pointed), url)
1965 ):
1966 links = [pointed, *(link for link in links if link != pointed)]
1967 for link in links[:_LINKED_PAGE_LIMIT]:
1968 if _out_of_time(f"the jobs page {link}"):
1969 break
1970 linked, _no_answer = _careers_text(link, guessed=guessed)
1971 landed = (budget.get_landed(link) if budget is not None else None) or link
1972 if not linked or not board_detect.is_safe_public_url(landed):
1973 continue
1974 landed_host = _host(landed)
1975 if not (
1976 _same_site(landed_host, _host(url))
1977 or _named_jobs_host(landed_host, url)
1978 or _jobs_host(landed_host)
1979 ):
1980 continue
1981 if _names_board(linked, landed):
1982 return linked, landed
1983 return html, url
1984
1985
1986 def _named_jobs_host(host: str, page_url: str) -> bool:
1987 """A jobs host on another domain that carries the page's site name:
1988 ``explore.jobs.netflix.net`` for a page on ``jobs.netflix.com``."""
1989 name = board_detect.registrable_label(_host(page_url))
1990 if not name or len(name) < 3 or name in _GENERIC_HOST_LABELS:
1991 return False
1992 cand = (host or "").strip().rstrip(".").lower()
1993 cand_url = f"https://{cand}/"
1994 if not cand or not board_detect.is_safe_public_url(cand_url) or board_detect.page_host(cand_url) != cand:
1995 return False
1996 return _jobs_host(cand) and board_detect.registrable_label(cand) == name
1997
1998
1999 def _jobs_links(html: str, page_url: str) -> list[str]:
2000 """Links on a careers page to a jobs page, best first: a jobs or careers
2001 host of its own site, then a path of its own host that reads like a job
2002 search, then a jobs host on another domain that carries the site's name
2003 (``_named_jobs_host``). A link to the page itself or to another page of
2004 the same kind (a translation of it, "life at") is left out."""
2005 page_host = _host(page_url)
2006 if not page_host or not board_detect.is_safe_public_url(page_url):
2007 return []
2008 ranked: list[tuple[int, str]] = []
2009 seen_links: set[str] = set()
2010 for href in re.findall(r"""href\s*=\s*["']([^"'#\s]+)""", (html or "")[:board_detect.MAX_HTML_CHARS], flags=re.I):
2011 link = urljoin(page_url, unescape(href))
2012 if link in seen_links:
2013 continue
2014 seen_links.add(link)
2015 if not board_detect.is_safe_public_url(link):
2016 continue
2017 parsed = urlparse(link)
2018 host = (parsed.hostname or "").rstrip(".").lower()
2019 if not _same_site(host, page_host):
2020 if not _named_jobs_host(host, page_url) or _FILE_LINK.search(parsed.path):
2021 continue
2022 rank = 2
2023 elif _FILE_LINK.search(parsed.path):
2024 continue
2025 elif host != page_host and _jobs_host(host):
2026 rank = 0
2027 elif host == page_host and _JOBS_LINK_WORDS.search(parsed.path):
2028 rank = 1
2029 else:
2030 continue
2031 ranked.append((rank, link))
2032 return [link for _rank, link in sorted(ranked, key=lambda entry: entry[0])]
2033
2034
2035 def _same_site(host: str, site_host: str) -> bool:
2036 """Whether ``host`` is the site's own host or a subdomain of it."""
2037 return board_detect.same_host_or_subdomain(host, site_host)
2038
2039
2040 def _search_for_careers_url(
2041 company: str,
2042 date_range: tuple[str, str],
2043 config: dict[str, Any],
2044 *,
2045 backend: str = "auto",
2046 ) -> str | None:
2047 """Use the configured web backend to locate the careers page URL."""
2048 try:
2049 raw_items, _ = grounding.web_search(
2050 f"{company} careers jobs", date_range, config, backend=backend,
2051 )
2052 except Exception:
2053 return None
2054 for raw in raw_items or []:
2055 if not isinstance(raw, dict):
2056 continue
2057 url = str(raw.get("url") or "").strip()
2058 if not url or not board_detect.is_safe_public_url(url) or _is_search_redirect(url):
2059 # An ad or a search engine's own redirect is no one's careers page.
2060 continue
2061 lowered = url.lower()
2062 if any(token in lowered for token in (
2063 "career", "/jobs", "ashbyhq", "greenhouse", "lever.co", "workable", "smartrecruiters",
2064 "myworkdayjobs",
2065 )):
2066 return url
2067 return None
2068
2069
2070 _SEARCH_ENGINE_HOSTS = ("duckduckgo.com", "bing.com", "google.com", "yahoo.com", "brave.com")
2071 _REDIRECT_PATH = re.compile(r"^/(?:y\.js|l/?|url|aclk|ck/a|r|rd)(?:$|[/?])", re.I)
2072
2073
2074 def _is_search_redirect(url: str) -> bool:
2075 """Whether a URL is a search engine's ad or click-through link
2076 (``duckduckgo.com/y.js?ad_domain=...``, ``duckduckgo.com/l/?uddg=...``,
2077 ``google.com/url?q=...``, ``bing.com/aclk``) rather than a page."""
2078 try:
2079 parsed = urlparse(url if "://" in url else f"https:{url}" if url.startswith("//") else f"https://{url}")
2080 _ = parsed.port
2081 except ValueError:
2082 return True
2083 if parsed.username is not None or parsed.password is not None:
2084 return True
2085 host = (parsed.hostname or "").rstrip(".").lower()
2086 if not any(_same_site(host, engine) for engine in _SEARCH_ENGINE_HOSTS):
2087 return False
2088 query = parsed.query.lower()
2089 return bool(
2090 _REDIRECT_PATH.match(parsed.path or "/")
2091 or "ad_domain=" in query or "uddg=" in query
2092 )
2093
2094
2095 # One posting on a supported board: the URL shapes each provider gives a role.
2096 _POSTING_URL_PATTERNS: tuple[str, ...] = (
2097 r"^(?:boards|job-boards)(?:\.eu)?\.greenhouse\.io/([A-Za-z0-9_.-]+)/jobs/\d+",
2098 r"^jobs\.ashbyhq\.com/([A-Za-z0-9_.%-]+)/[0-9a-f-]{20,}",
2099 r"^jobs\.(?:eu\.)?lever\.co/([A-Za-z0-9_.-]+)/[0-9a-f-]{20,}",
2100 r"^apply\.workable\.com/([A-Za-z0-9_.-]+)/j/[A-Za-z0-9]+",
2101 r"^jobs\.smartrecruiters\.com/([A-Za-z0-9_.-]+)/\d+",
2102 r"^([A-Za-z0-9_-]+)\.wd[0-9]+\.myworkdayjobs\.com/(?:[^?#]*/)?job/[^?#]+",
2103 )
2104
2105
2106 def _posting_board(url: str) -> str:
2107 """The board slug when ``url`` is one job posting on a supported board,
2108 else ''. A board's front page, a careers landing page, a news story or a
2109 search engine's link is not a posting."""
2110 raw = (url or "").strip()
2111 if not raw or "\\" in raw or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw):
2112 return ""
2113 try:
2114 parsed = urlparse(raw)
2115 port = parsed.port
2116 except ValueError:
2117 return ""
2118 scheme = parsed.scheme.lower()
2119 if scheme not in ("http", "https"):
2120 return ""
2121 if parsed.username is not None or parsed.password is not None:
2122 return ""
2123 if port is not None and not (
2124 (scheme == "https" and port == 443) or (scheme == "http" and port == 80)
2125 ):
2126 return ""
2127 host = (parsed.hostname or "").rstrip(".").lower().removeprefix("www.")
2128 if not host:
2129 return ""
2130 target = host + parsed.path
2131 for pattern in _POSTING_URL_PATTERNS:
2132 match = re.match(pattern, target, flags=re.I)
2133 if match:
2134 return match.group(1)
2135 return ""
2136
2137
2138 def _host(url: str) -> str:
2139 raw = (url or "").strip()
2140 if not raw or "\\" in raw or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw):
2141 return ""
2142 try:
2143 parsed = urlparse(raw if "://" in raw else f"https://{raw}")
2144 _ = parsed.port
2145 except ValueError:
2146 return ""
2147 if parsed.username is not None or parsed.password is not None:
2148 return ""
2149 raw_host = (parsed.hostname or "").lower()
2150 if not raw_host or "\\" in raw_host or ".." in raw_host or raw_host.startswith("."):
2151 return ""
2152 return raw_host.rstrip(".")
2153
2154
2155 def _site_hosts(company: str, site: str = "") -> list[str]:
2156 """Hosts whose careers page is tried: the known official site alone, or,
2157 when no site is known, domains guessed from the company's name."""
2158 if site and _host(site):
2159 return [_host(site)]
2160 slug = _company_slug(company)
2161 return [f"{slug}.com", f"{slug}.ai", f"{slug}.io"] if slug else []
2162
2163
2164 def _found_via(careers_url: str, company: str, site: str = "") -> str:
2165 """How the careers page naming the board was reached.
2166
2167 ``site`` is the known official site, the only one that makes a board the
2168 company's own; a page on a subdomain of it (``jobs.nvidia.com`` for
2169 ``www.nvidia.com``) is the same site. ``guess`` is a domain guessed from
2170 the company's name, which another business can own, and ``search`` is a
2171 web search result.
2172 """
2173 host = _host(careers_url)
2174 if site and host and _same_site(host, _host(site)):
2175 return "site"
2176 guessed = any(_same_site(host, guess) for guess in _site_hosts(company))
2177 return "guess" if guessed else "search"
2178
2179
2180 def _same_company(stated: str, company: str) -> bool:
2181 """Whether a board's stated company name is the company being researched."""
2182 return bool(set(_candidate_slugs(stated)) & set(_candidate_slugs(company)))
2183
2184
2185 def _names_overlap(stated: str, company: str) -> bool:
2186 """Whether a board's stated name could be a longer or shorter form of the
2187 company's ("Meta Platforms" for "Meta"). Looser than ``_same_company``:
2188 it only tells a namesake's board from one that may be the company's."""
2189 one, other = _company_slug(stated), _company_slug(company)
2190 if min(len(one), len(other)) < 3:
2191 return one == other
2192 return one in other or other in one
2193
2194
2195 def _name_words(name: str) -> list[str]:
2196 text = re.sub(r"['\u2019.]", "", name.lower())
2197 text = re.sub(r"\b(inc|llc|ltd|corp|corporation|company|co)\b", " ", text)
2198 return re.sub(r"[^a-z0-9]+", " ", text).split()
2199
2200
2201 def _leads_with(stated: str, company: str) -> bool:
2202 """Whether one name is the other with whole words added at its end
2203 ("Anduril Industries" for "Anduril"; never "Metabase" for "Meta").
2204
2205 Looser than ``_same_company``, so it never makes a board found by a
2206 guessed slug the company's: it is used where something besides the slug
2207 points at the board (the host passed its URL, or the company's careers
2208 page states the longer name)."""
2209 one, other = _name_words(stated), _name_words(company)
2210 short, long = sorted((one, other), key=len)
2211 return bool(short) and long[:len(short)] == short
2212
2213
2214 def _board_counts(
2215 items: list[dict[str, Any]], board: dict[str, Any], date_range: tuple[str, str],
2216 ) -> dict[str, Any]:
2217 """What the board itself reports: open roles, and roles new in the window.
2218
2219 ``open_roles_floor`` marks a count the board stopped short of (its row
2220 ceiling, or a listing cut short). ``new_in_window`` is a number only when
2221 the whole board was read and every role carries a true first-posted date;
2222 otherwise it is None. A board read newest first (``board_newest_first``)
2223 reports its own total instead, see below.
2224 """
2225 from_date, to_date = date_range
2226 if board.get("board_newest_first") or board.get("board_reports_total"):
2227 # A board that reports its own total, read newest first or in its own
2228 # order up to a ceiling: the open-role count is the total it reports,
2229 # and the roles new in the window are counted only when the read
2230 # covered the window (went past its oldest day, or read the board).
2231 covered = bool(board.get("board_window_covered"))
2232 return {
2233 "open_roles": max(int(board.get("board_total") or 0), len(items)),
2234 "open_roles_floor": bool(board.get("board_total_floor")),
2235 "new_in_window": (
2236 sum(
2237 1 for item in items
2238 if item.get("posted_date_true") and item.get("date")
2239 and from_date <= str(item["date"]) <= to_date
2240 )
2241 if covered else None
2242 ),
2243 }
2244 floor = bool(board.get("board_capped") or board.get("board_cut_short"))
2245 dated = not floor and all(
2246 item.get("posted_date_true") and item.get("date") for item in items
2247 )
2248 return {
2249 "open_roles": len(items),
2250 "open_roles_floor": floor,
2251 "new_in_window": (
2252 sum(1 for item in items if from_date <= str(item["date"]) <= to_date)
2253 if dated else None
2254 ),
2255 }
2256
2257
2258 def detect_ats(html: str) -> tuple[str | None, str | None]:
2259 """Read the ATS provider + slug off a careers page's embed/links."""
2260 if not html:
2261 return None, None
2262 bounded = html[:board_detect.MAX_HTML_CHARS]
2263 for provider, pattern in _ATS_LINK_PATTERNS:
2264 for match in re.finditer(pattern, bounded):
2265 slug = match.group(match.lastindex or 1).strip().strip("/.")
2266 if not slug or slug.lower() in _SLUG_STOPWORDS:
2267 continue
2268 if provider == ATS_PROVIDER_WORKDAY:
2269 # One token carries all three parts: "tenant.wdN/site".
2270 slug = f"{match.group(1)}.{match.group(2)}/{slug}"
2271 return provider, slug
2272 return None, None
2273
2274
2275 def _probe_ats(company: str) -> tuple[str | None, str | None, list[str]]:
2276 """Fallback: probe candidate slugs against ATS APIs (deterministic).
2277
2278 Only reached when careers-page discovery fails. Returns the first provider
2279 whose API returns a non-empty board.
2280 """
2281 provider, slug, attempts, _items = _probe_boards(company)
2282 return provider, slug, attempts
2283
2284
2285 # Slugs tried beyond the company's own: those of the names its careers page states.
2286 _STATED_SLUG_LIMIT = 4
2287
2288
2289 def _probe_boards(
2290 company: str,
2291 *,
2292 also: list[str] | None = None,
2293 ) -> tuple[str | None, str | None, list[str], list[dict[str, Any]] | None]:
2294 """``_probe_ats`` plus the rows of the board it found, so the caller does
2295 not read that board a second time.
2296
2297 A board found by a guessed slug that states another company's name is
2298 someone else's board under the same slug, and is passed over. A probe the
2299 lane's budget cut off ends the probing; any other failure of a board's API
2300 is an outage and is raised, naming the provider and slug.
2301
2302 ``also`` are other names for the company (what its careers page calls
2303 its organization); their slugs are tried after the company's own.
2304 """
2305 attempts: list[str] = []
2306 slugs = _candidate_slugs(company)
2307 more = [
2308 slug for name in also or [] for slug in _candidate_slugs(name) if slug not in slugs
2309 ]
2310 slugs += list(dict.fromkeys(more))[:_STATED_SLUG_LIMIT]
2311 # Workable/SmartRecruiters are omitted here: their slugs rarely match the
2312 # company name, so blind probing is unreliable - they're reached only via
2313 # careers-page discovery, where the real slug is published.
2314 for slug in slugs:
2315 for provider in (ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER):
2316 if _out_of_time(f"the {provider} probe for the slug {slug}"):
2317 return None, None, attempts, None
2318 attempts.append(f"probe:{provider}:{slug}")
2319 try:
2320 with http.expected_misses(400, 401, 403, 404):
2321 items = _fetch_ats(provider, slug)
2322 except http.DeadlineExceeded:
2323 # The request's hard deadline is the earlier of its own
2324 # limit and the time the lane has left (``_bounds``). Only
2325 # the second ends the probing; a provider that used up its
2326 # own limit is that probe's failure, and the next is asked.
2327 budget = _BUDGET.get()
2328 if budget is not None:
2329 budget.note_slow(f"the {provider} API had not answered for the slug {slug}")
2330 if budget.remaining() <= 0:
2331 budget.stop(f"the {provider} probe for the slug {slug} answered")
2332 return None, None, attempts, None
2333 budget.note_unanswered(
2334 f"the {provider} API did not answer for the slug {slug}"
2335 )
2336 attempts.append(f"no-answer:{provider}:{slug}")
2337 continue
2338 except http.HTTPError as exc:
2339 if exc.status_code in {400, 401, 403, 404}:
2340 continue
2341 failure = http.HTTPError(
2342 f"{provider} board API failed for the guessed slug {slug!r}: {exc}",
2343 status_code=exc.status_code,
2344 body=exc.body,
2345 outcome_state=exc.outcome_state,
2346 )
2347 failure.no_host = exc.no_host
2348 raise failure from exc
2349 if not items:
2350 continue
2351 stated = next(
2352 (str(item["company_name"]) for item in items if item.get("company_name")), "",
2353 )
2354 if stated and not _names_overlap(stated, company):
2355 attempts.append(f"not-the-company:{provider}:{slug}")
2356 continue
2357 return provider, slug, attempts, items
2358 return None, None, attempts, None
2359
2360
2361 # --------------------------------------------------------------------------- #
2362 # Tier 1: ATS API fetchers + parsers
2363 # --------------------------------------------------------------------------- #
2364
2365 def _fetch_ats(provider: str, slug: str, *, retries: int = 2) -> list[dict[str, Any]]:
2366 fetchers: dict[str, Callable[..., list[dict[str, Any]]]] = {
2367 ATS_PROVIDER_GREENHOUSE: search_greenhouse_board,
2368 ATS_PROVIDER_ASHBY: search_ashby_board,
2369 ATS_PROVIDER_LEVER: search_lever_board,
2370 ATS_PROVIDER_WORKABLE: search_workable_board,
2371 ATS_PROVIDER_SMARTRECRUITERS: search_smartrecruiters_board,
2372 }
2373 fetcher = fetchers.get(provider)
2374 if not fetcher:
2375 return []
2376 # Only the three providers a slug is probed on take an attempt count.
2377 if retries != 2 and provider in (
2378 ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER,
2379 ):
2380 return fetcher(slug, retries=retries)
2381 return fetcher(slug)
2382
2383
2384 def search_greenhouse_board(board_token: str, *, retries: int = 2) -> list[dict[str, Any]]:
2385 """Return jobs from Greenhouse's public Job Board API."""
2386 url = f"https://boards-api.greenhouse.io/v1/boards/{board_token}/jobs"
2387 data = http.get(
2388 url, params={"content": "true"}, retries=retries,
2389 **_bounds(API_TIMEOUT_SECONDS, retries),
2390 )
2391 jobs = data.get("jobs") if isinstance(data, dict) else []
2392 if not isinstance(jobs, list):
2393 return []
2394 return [_greenhouse_job_to_item(job, board_token) for job in jobs if isinstance(job, dict)]
2395
2396
2397 def search_ashby_board(slug: str, *, retries: int = 2) -> list[dict[str, Any]]:
2398 """Return jobs from Ashby's public posting API (needs a browser UA)."""
2399 url = f"https://api.ashbyhq.com/posting-api/job-board/{slug}"
2400 data = http.get(
2401 url,
2402 params={"includeCompensation": "true"},
2403 headers={"User-Agent": http.BROWSER_USER_AGENT},
2404 retries=retries,
2405 **_bounds(API_TIMEOUT_SECONDS, retries),
2406 )
2407 return parse_ashby_response(data, slug)
2408
2409
2410 def search_lever_board(slug: str, *, retries: int = 2) -> list[dict[str, Any]]:
2411 """Return jobs from Lever's public postings API (returns a JSON list)."""
2412 url = f"https://api.lever.co/v0/postings/{slug}"
2413 data = http.get(
2414 url, params={"mode": "json"}, retries=retries, **_bounds(API_TIMEOUT_SECONDS, retries),
2415 )
2416 return parse_lever_response(data, slug)
2417
2418
2419 def search_workable_board(slug: str) -> list[dict[str, Any]]:
2420 """Return jobs from Workable's public widget API."""
2421 return read_workable_board(slug)[0]
2422
2423
2424 def read_workable_board(slug: str) -> tuple[list[dict[str, Any]], dict[str, Any]]:
2425 """Return the first page of a Workable board and what was read of it.
2426
2427 Only that page is read. When the board reports more roles than the page
2428 holds, ``board_cut_short`` says so; the keys are ``search_workday_board``'s.
2429 """
2430 url = f"https://apply.workable.com/api/v3/accounts/{slug}/jobs"
2431 data = http.post(url, json_data={}, retries=2, **_bounds(API_TIMEOUT_SECONDS, 2))
2432 items = parse_workable_response(data, slug)
2433 total = max(_reported_total(data, "total"), len(items))
2434 return items, {
2435 "board_total": total, "board_capped": False, "board_cut_short": total > len(items),
2436 }
2437
2438
2439 def search_smartrecruiters_board(slug: str) -> list[dict[str, Any]]:
2440 """Return jobs from SmartRecruiters' public postings API."""
2441 return read_smartrecruiters_board(slug)[0]
2442
2443
2444 def _reported_total(payload: Any, key: str) -> int:
2445 try:
2446 return int(payload.get(key) or 0) if isinstance(payload, dict) else 0
2447 except (TypeError, ValueError):
2448 return 0
2449
2450
2451 def read_smartrecruiters_board(
2452 slug: str,
2453 *,
2454 deadline: float | None = None,
2455 budget_seconds: float = WORKDAY_BUDGET_SECONDS,
2456 clock: Callable[[], float] | None = None,
2457 first_page_only: bool = False,
2458 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
2459 """Return a SmartRecruiters board's rows and what was read of the board.
2460
2461 The board is read a page at a time up to the row ceiling. The second value
2462 has the same keys as ``search_workday_board``'s: ``board_capped`` when the
2463 board reports more rows than the ceiling, ``board_cut_short`` when the time
2464 budget ran out or a page failed. A failed first page returns no rows.
2465 ``first_page_only`` reads that page alone, for a board not yet known to
2466 be the company's.
2467 """
2468 info: dict[str, Any] = {"board_total": 0, "board_capped": False, "board_cut_short": False}
2469 url = f"https://api.smartrecruiters.com/v1/companies/{slug}/postings"
2470 clock = clock or _clock()
2471 deadline = _workday_deadline(deadline, budget_seconds, clock)
2472
2473 def page(offset: int) -> Callable[[float], Any]:
2474 params = {"limit": str(SMARTRECRUITERS_PAGE_SIZE)}
2475 if offset:
2476 params["offset"] = str(offset)
2477 return lambda http_deadline: http.get(
2478 url, params=params, timeout=API_TIMEOUT_SECONDS, retries=2,
2479 deadline_monotonic=http_deadline, public_only=True,
2480 )
2481
2482 first, unanswered = _run_first_page(page(0), deadline, clock)
2483 if not isinstance(first, dict):
2484 if unanswered:
2485 info["board_unanswered"] = True
2486 return [], info
2487 items = parse_smartrecruiters_response(first, slug)
2488 total = max(_reported_total(first, "totalFound"), len(items))
2489 info["board_total"] = total
2490 info["board_capped"] = total > SMARTRECRUITERS_ROW_CEILING
2491 if first_page_only:
2492 # With no reported total, a full page may not be the whole board.
2493 info.update(
2494 board_cut_short=total > len(items) or (
2495 "totalFound" not in first and len(items) >= SMARTRECRUITERS_PAGE_SIZE
2496 ),
2497 board_first_page_only=True,
2498 )
2499 return items, info
2500 rest = _workday_run(
2501 [
2502 page(offset)
2503 for offset in range(
2504 SMARTRECRUITERS_PAGE_SIZE,
2505 min(total, SMARTRECRUITERS_ROW_CEILING),
2506 SMARTRECRUITERS_PAGE_SIZE,
2507 )
2508 ],
2509 deadline,
2510 clock,
2511 )
2512 # A full page from a board that reports no total may not be the last one.
2513 info["board_cut_short"] = any(not isinstance(payload, dict) for payload in rest) or (
2514 "totalFound" not in first and len(items) >= SMARTRECRUITERS_PAGE_SIZE
2515 )
2516 for payload in rest:
2517 if isinstance(payload, dict):
2518 items.extend(parse_smartrecruiters_response(payload, slug))
2519 return items[:SMARTRECRUITERS_ROW_CEILING], info
2520
2521
2522 # Workday: a paginated listing with no descriptions, plus one detail call per
2523 # role. The board token is "tenant.wdN/site", as detect_ats builds it.
2524
2525 def _workday_parts(token: str) -> tuple[str, str] | None:
2526 """Split a board token into (host, API base URL), or None if malformed."""
2527 match = re.fullmatch(r"([A-Za-z0-9_-]+)\.(wd[0-9]+)/([A-Za-z0-9_-]+)", token or "")
2528 if not match:
2529 return None
2530 tenant, number, site = match.groups()
2531 host = f"https://{tenant}.{number}.myworkdayjobs.com"
2532 return host, f"{host}/wday/cxs/{tenant}/{site}"
2533
2534
2535 def workday_list_url(token: str) -> str:
2536 parts = _workday_parts(token)
2537 return f"{parts[1]}/jobs" if parts else ""
2538
2539
2540 def _workday_deadline(
2541 deadline: float | None, budget_seconds: float, clock: Callable[[], float],
2542 ) -> float:
2543 return clock() + budget_seconds if deadline is None else deadline
2544
2545
2546 _OUT_OF_TIME = object()
2547
2548
2549 def _workday_run(
2550 calls: list[Callable[[float], Any]],
2551 deadline: float,
2552 clock: Callable[[], float],
2553 ) -> list[Any]:
2554 """Run calls at most WORKDAY_MAX_WORKERS at once; results keep call order.
2555
2556 A call that fails yields None; one that would start after the deadline
2557 yields ``_OUT_OF_TIME``. Each call gets the monotonic deadline to hand to
2558 ``lib.http``.
2559 """
2560 def run(call: Callable[[float], Any]) -> Any:
2561 remaining = deadline - clock()
2562 if remaining <= 0:
2563 return _OUT_OF_TIME
2564 try:
2565 # Each call makes up to two attempts; one page or detail that
2566 # never finishes is cut off at its own limit, not the board's.
2567 return call(time.monotonic() + min(remaining, _request_seconds(API_TIMEOUT_SECONDS, 2)))
2568 except http.HTTPError:
2569 return None
2570
2571 if not calls:
2572 return []
2573 with ThreadPoolExecutor(max_workers=min(WORKDAY_MAX_WORKERS, len(calls))) as executor:
2574 futures = [http.submit_with_context(executor, run, call) for call in calls]
2575 return [future.result() for future in futures]
2576
2577
2578 def _run_first_page(
2579 call: Callable[[float], Any],
2580 deadline: float,
2581 clock: Callable[[], float],
2582 ) -> tuple[Any, bool]:
2583 """Run a board's first listing page and report whether it went unanswered.
2584
2585 No answer (deadline spent, timeout/transport error with ``status_code is
2586 None``), an overload (5xx), or a rate limit (429) is retryable and marks
2587 the board unanswered rather than permanently unreadable or absent.
2588 """
2589 failures: list[http.HTTPError] = []
2590
2591 def tracked(http_deadline: float) -> Any:
2592 try:
2593 return call(http_deadline)
2594 except http.HTTPError as exc:
2595 failures.append(exc)
2596 raise
2597
2598 first = _workday_run([tracked], deadline, clock)[0]
2599 if first is None or first is _OUT_OF_TIME:
2600 status = failures[0].status_code if failures else None
2601 unanswered = first is _OUT_OF_TIME or status is None or status == 429 or status >= 500
2602 return first, unanswered
2603 return first, False
2604
2605
2606 def _workday_body(offset: int, search_text: str = "") -> dict[str, Any]:
2607 return {
2608 "appliedFacets": {},
2609 "limit": WORKDAY_PAGE_SIZE,
2610 "offset": offset,
2611 "searchText": search_text,
2612 }
2613
2614
2615 def search_workday_story(
2616 token: str, term: str, *, deadline_monotonic: float,
2617 ) -> list[dict[str, Any]]:
2618 """The roles a Workday site's own search finds for a story term."""
2619 url = workday_list_url(token)
2620 if not url or board_robots.disallowed(url, deadline_monotonic=deadline_monotonic):
2621 return []
2622 payload = http.post(
2623 url, json_data=_workday_body(0, term), headers={"Accept": "application/json"},
2624 timeout=STORY_TIMEOUT_SECONDS, retries=1, deadline_monotonic=deadline_monotonic,
2625 )
2626 return parse_workday_response(payload, token) if isinstance(payload, dict) else []
2627
2628
2629 def search_workday_board(
2630 token: str,
2631 *,
2632 deadline: float | None = None,
2633 budget_seconds: float = WORKDAY_BUDGET_SECONDS,
2634 clock: Callable[[], float] | None = None,
2635 first_page_only: bool = False,
2636 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
2637 """Return a Workday board's listing rows and what was read of the board.
2638
2639 The second value has ``board_total`` (the count the board reports, which
2640 Workday itself stops at the row ceiling), ``board_capped`` (the listing hit
2641 that ceiling, so the board may be larger) and ``board_cut_short`` (the time
2642 budget ran out or a page failed, so some reported rows were not read).
2643 A failed first page returns no rows rather than raising.
2644 """
2645 info: dict[str, Any] = {"board_total": 0, "board_capped": False, "board_cut_short": False}
2646 url = workday_list_url(token)
2647 if not url:
2648 return [], info
2649 clock = clock or _clock()
2650 deadline = _workday_deadline(deadline, budget_seconds, clock)
2651
2652 def page(offset: int) -> Callable[[float], Any]:
2653 return lambda http_deadline: http.post(
2654 url,
2655 json_data=_workday_body(offset),
2656 headers={"Accept": "application/json"},
2657 timeout=API_TIMEOUT_SECONDS,
2658 retries=2,
2659 deadline_monotonic=http_deadline,
2660 )
2661
2662 # The total is reported on the first page only, so read that one first.
2663 first, unanswered = _run_first_page(page(0), deadline, clock)
2664 if not isinstance(first, dict) or not isinstance(first.get("jobPostings"), list):
2665 if unanswered:
2666 info["board_unanswered"] = True
2667 # Not a listing: a site name the tenant does not have answers an
2668 # error record, which is not paged through.
2669 return [], info
2670 try:
2671 total = int(first.get("total") or 0)
2672 except (TypeError, ValueError):
2673 total = 0
2674 info["board_total"] = total
2675 info["board_capped"] = total >= WORKDAY_ROW_CEILING
2676 wanted = min(total, WORKDAY_ROW_CEILING)
2677 if first_page_only:
2678 # For a board not yet known to be the company's.
2679 items = parse_workday_response(first, token)
2680 info.update(board_cut_short=total > len(items), board_first_page_only=True)
2681 return items, info
2682 rest = _workday_run(
2683 [page(offset) for offset in range(WORKDAY_PAGE_SIZE, wanted, WORKDAY_PAGE_SIZE)],
2684 deadline,
2685 clock,
2686 )
2687 info["board_cut_short"] = any(not isinstance(payload, dict) for payload in rest)
2688
2689 items: list[dict[str, Any]] = []
2690 for payload in [first, *rest]:
2691 if isinstance(payload, dict):
2692 items.extend(parse_workday_response(payload, token))
2693 return items[:WORKDAY_ROW_CEILING], info
2694
2695
2696 # Paths a Workday host's robots.txt lists that are not career sites.
2697 _WORKDAY_NON_SITES = {"refreshfacet", "wday"}
2698
2699
2700 def workday_tenant_sites(
2701 token: str,
2702 named: set[tuple[str, str]] | frozenset[tuple[str, str]] = frozenset(),
2703 *,
2704 deadline_monotonic: float | None = None,
2705 ) -> list[str]:
2706 """The other career sites of a Workday board's tenant, as board tokens.
2707
2708 A tenant can run several sites (Nike: ``nke``, ``nke2``, ``nke4``). They
2709 are the first path segment of every ``Allow``, ``Disallow`` and
2710 ``Sitemap`` line of the tenant host's robots.txt, and the Workday boards
2711 a careers page names (``named``, as ``_boards_named`` gives them) on the
2712 same tenant. A site on another tenant is another company's and is left
2713 out. Candidates are not checked here: a name that is not a site answers
2714 its listing call with something other than a listing.
2715 """
2716 parts = _workday_parts(token)
2717 if not parts:
2718 return []
2719 tenant_host, site = token.split("/", 1)
2720 tenant = tenant_host.split(".", 1)[0].lower()
2721 found: dict[str, str] = {site.lower(): token}
2722 for provider, slug in sorted(named):
2723 if provider == ATS_PROVIDER_WORKDAY and slug.split(".", 1)[0] == tenant:
2724 # ``_boards_named`` lower-cases its slugs; Workday site names are
2725 # not case sensitive.
2726 found.setdefault(slug.split("/", 1)[1], slug)
2727 rules = board_robots.rules_for(
2728 urlparse(parts[0]).hostname or "", deadline_monotonic=deadline_monotonic,
2729 )
2730 for path in [*rules.paths, *(urlparse(url).path for url in rules.sitemaps)]:
2731 first = path.strip("/").split("/", 1)[0]
2732 if re.fullmatch(r"[A-Za-z0-9_-]+", first) and first.lower() not in _WORKDAY_NON_SITES:
2733 found.setdefault(first.lower(), f"{tenant_host}/{first}")
2734 found.pop(site.lower())
2735 return list(found.values())
2736
2737
2738 def _workday_job_key(item: dict[str, Any]) -> str:
2739 """A Workday role's ``externalPath``, which is the same on every site of
2740 the tenant that lists the role."""
2741 token = str(item.get("board_token") or "")
2742 url = str(item.get("url") or "")
2743 parts = _workday_parts(token)
2744 prefix = f"{parts[0]}/{token.split('/', 1)[1]}" if parts else ""
2745 return (url[len(prefix):] if prefix and url.startswith(prefix) else url).lower()
2746
2747
2748 def read_workday_tenant_sites(
2749 token: str,
2750 items: list[dict[str, Any]],
2751 info: dict[str, Any],
2752 others: list[str],
2753 *,
2754 deadline: float,
2755 clock: Callable[[], float] | None = None,
2756 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
2757 """Add the tenant's other career sites to a Workday board already read.
2758
2759 ``items`` and ``info`` are what ``search_workday_board`` gave for
2760 ``token``; ``others`` are the sites ``workday_tenant_sites`` found. Each
2761 is read the same way, up to its own row ceiling, until
2762 ``COMPANY_BOARD_ROW_CEILING`` rows are held across sites. A role listed
2763 on two sites counts once. When a second site gives rows, ``board_sites``
2764 holds each site's role count, and the board's total, cap and cut-short
2765 flags cover every site read.
2766 """
2767 clock = clock or _clock()
2768 merged = list(items)
2769 seen = {_workday_job_key(item) for item in merged}
2770 sites = [{"site": token.split("/", 1)[1], "roles": len(items)}]
2771 totals = [min(int(info.get("board_total") or 0), WORKDAY_ROW_CEILING)]
2772 capped, cut_short = bool(info.get("board_capped")), bool(info.get("board_cut_short"))
2773 for other in others:
2774 if len(merged) >= COMPANY_BOARD_ROW_CEILING:
2775 capped = True
2776 break
2777 listing = workday_list_url(other)
2778 if board_robots.disallowed(
2779 listing, deadline_monotonic=time.monotonic() + max(0.0, deadline - clock()),
2780 ):
2781 continue
2782 rows, read = search_workday_board(other, deadline=deadline, clock=clock)
2783 for row in rows:
2784 key = _workday_job_key(row)
2785 if key not in seen:
2786 seen.add(key)
2787 merged.append(row)
2788 if not rows:
2789 continue
2790 sites.append({"site": other.split("/", 1)[1], "roles": len(rows)})
2791 totals.append(min(int(read.get("board_total") or 0), WORKDAY_ROW_CEILING))
2792 capped = capped or bool(read.get("board_capped"))
2793 cut_short = cut_short or bool(read.get("board_cut_short"))
2794 if len(sites) < 2:
2795 return items, info
2796 if len(merged) > COMPANY_BOARD_ROW_CEILING:
2797 capped = True
2798 log.source_log(
2799 "Jobs",
2800 "Workday tenant sites read: "
2801 + ", ".join(f"{site['site']} ({site['roles']:,})" for site in sites)
2802 + f"; {min(len(merged), COMPANY_BOARD_ROW_CEILING):,} distinct roles",
2803 tty_only=False,
2804 )
2805 return merged[:COMPANY_BOARD_ROW_CEILING], {
2806 **info,
2807 "board_total": min(sum(totals), COMPANY_BOARD_ROW_CEILING),
2808 "board_capped": capped,
2809 "board_cut_short": cut_short,
2810 "board_row_ceiling": COMPANY_BOARD_ROW_CEILING,
2811 "board_sites": sites,
2812 }
2813
2814
2815 def parse_workday_response(payload: dict[str, Any], token: str = "") -> list[dict[str, Any]]:
2816 """Parse one Workday listing page. Rows have no description or posted date:
2817 ``postedOn`` is a relative label ("Posted 3 Days Ago"), so it is not read
2818 as a date."""
2819 postings = payload.get("jobPostings") if isinstance(payload, dict) else []
2820 parts = _workday_parts(token)
2821 if not isinstance(postings, list) or not parts:
2822 return []
2823 site_url = f"{parts[0]}/{token.split('/', 1)[1]}"
2824 items: list[dict[str, Any]] = []
2825 for job in postings:
2826 if not isinstance(job, dict):
2827 continue
2828 title = str(job.get("title") or "").strip()
2829 path = str(job.get("externalPath") or "").strip()
2830 if not title or not path.startswith("/"):
2831 continue
2832 bullets = job.get("bulletFields") if isinstance(job.get("bulletFields"), list) else []
2833 ident = str(bullets[0]).strip() if bullets else path.rsplit("/", 1)[-1]
2834 items.append(_ats_item(
2835 provider=ATS_PROVIDER_WORKDAY,
2836 slug=token,
2837 ident=ident,
2838 title=title,
2839 url=f"{site_url}{path}",
2840 description="",
2841 date=None,
2842 department="",
2843 location=str(job.get("locationsText") or "").strip(),
2844 # One row is one requisition with all its locations ("2 Locations").
2845 whole_posting=True,
2846 ))
2847 return items
2848
2849
2850 def fetch_workday_details(
2851 items: list[dict[str, Any]],
2852 *,
2853 deadline: float | None = None,
2854 budget_seconds: float = WORKDAY_BUDGET_SECONDS,
2855 clock: Callable[[], float] | None = None,
2856 ) -> tuple[int, int]:
2857 """Fill ``description`` and the true posted date on the given Workday items.
2858
2859 One call per item, so pass only the few roles that need it. An item whose
2860 call fails, or would start after the deadline, is left as it was. Returns
2861 two counts of items left unfetched: those the deadline stopped before
2862 their call started, and those whose call failed or returned no posting.
2863 """
2864 clock = clock or _clock()
2865 deadline = _workday_deadline(deadline, budget_seconds, clock)
2866
2867 def detail(item: dict[str, Any]) -> Callable[[float], Any]:
2868 parts = _workday_parts(str(item.get("board_token") or ""))
2869 site_url = f"{parts[0]}/{item['board_token'].split('/', 1)[1]}" if parts else ""
2870 url = str(item.get("url") or "")
2871 if not parts or not url.startswith(f"{site_url}/"):
2872 return lambda http_deadline: None
2873 detail_url = f"{parts[1]}{url[len(site_url):]}"
2874 return lambda http_deadline: http.get(
2875 detail_url,
2876 headers={"Accept": "application/json"},
2877 timeout=API_TIMEOUT_SECONDS,
2878 retries=2,
2879 deadline_monotonic=http_deadline,
2880 )
2881
2882 payloads = _workday_run([detail(item) for item in items], deadline, clock)
2883 late = failed = 0
2884 for item, payload in zip(items, payloads):
2885 posting = payload.get("jobPostingInfo") if isinstance(payload, dict) else None
2886 if not isinstance(posting, dict):
2887 if payload is _OUT_OF_TIME:
2888 late += 1
2889 else:
2890 failed += 1
2891 continue
2892 item["description"] = _clean_html(str(posting.get("jobDescription") or ""))
2893 item["description_blocks"] = _block_text(str(posting.get("jobDescription") or ""))
2894 posted = _date_part(posting.get("startDate"))
2895 if posted:
2896 item["date"] = posted
2897 item["date_confidence"] = "high"
2898 item["posted_date_true"] = True
2899 return late, failed
2900
2901
2902 def parse_greenhouse_response(payload: dict[str, Any], board_token: str = "") -> list[dict[str, Any]]:
2903 """Parse a Greenhouse jobs payload for tests and callers with cached data."""
2904 jobs = payload.get("jobs") if isinstance(payload, dict) else []
2905 if not isinstance(jobs, list):
2906 return []
2907 return [_greenhouse_job_to_item(job, board_token) for job in jobs if isinstance(job, dict)]
2908
2909
2910 def parse_ashby_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:
2911 jobs = payload.get("jobs") if isinstance(payload, dict) else []
2912 if not isinstance(jobs, list):
2913 return []
2914 items: list[dict[str, Any]] = []
2915 for job in jobs:
2916 if not isinstance(job, dict):
2917 continue
2918 department = str(job.get("departmentName") or job.get("teamName") or "").strip()
2919 location = str(job.get("locationName") or job.get("location") or "").strip()
2920 raw = str(job.get("descriptionHtml") or job.get("descriptionPlain") or "")
2921 published = _date_part(job.get("publishedDate") or job.get("publishedAt"))
2922 items.append(_ats_item(
2923 provider=ATS_PROVIDER_ASHBY,
2924 slug=slug,
2925 ident=str(job.get("id") or job.get("jobId") or ""),
2926 title=str(job.get("title") or "").strip(),
2927 url=str(job.get("jobUrl") or job.get("applyUrl") or "").strip(),
2928 description=_clean_html(raw),
2929 description_blocks=_block_text(raw),
2930 date=published,
2931 posted_date_true=bool(published),
2932 department=department,
2933 location=location,
2934 ))
2935 return items
2936
2937
2938 def parse_lever_response(payload: Any, slug: str = "") -> list[dict[str, Any]]:
2939 postings = payload if isinstance(payload, list) else []
2940 items: list[dict[str, Any]] = []
2941 for job in postings:
2942 if not isinstance(job, dict):
2943 continue
2944 categories = job.get("categories") if isinstance(job.get("categories"), dict) else {}
2945 department = str(categories.get("department") or categories.get("team") or "").strip()
2946 location = str(categories.get("location") or "").strip()
2947 raw = str(job.get("descriptionPlain") or job.get("description") or "")
2948 items.append(_ats_item(
2949 provider=ATS_PROVIDER_LEVER,
2950 slug=slug,
2951 ident=str(job.get("id") or ""),
2952 title=str(job.get("text") or "").strip(),
2953 url=str(job.get("hostedUrl") or job.get("applyUrl") or "").strip(),
2954 description=_clean_html(raw),
2955 description_blocks=_block_text(raw),
2956 # When the posting was created, which can be well before it went
2957 # public, so it is not counted as a posting date.
2958 date=_epoch_ms_to_date(job.get("createdAt")),
2959 department=department,
2960 location=location,
2961 ))
2962 return items
2963
2964
2965 def parse_workable_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:
2966 results = []
2967 if isinstance(payload, dict):
2968 results = payload.get("results") or payload.get("jobs") or []
2969 if not isinstance(results, list):
2970 return []
2971 items: list[dict[str, Any]] = []
2972 for job in results:
2973 if not isinstance(job, dict):
2974 continue
2975 loc = job.get("location") if isinstance(job.get("location"), dict) else {}
2976 location = _join_parts(str(loc.get("city") or ""), str(loc.get("country") or ""))
2977 # The v3 jobs endpoint gives `published` and a list of departments;
2978 # the older widget rows gave `published_on` and one department name.
2979 published = _date_part(job.get("published")) or _date_part(job.get("published_on"))
2980 raw_department = job.get("department")
2981 if isinstance(raw_department, (list, tuple)):
2982 department = _join_parts(*(str(name or "") for name in raw_department))
2983 else:
2984 department = str(raw_department or "").strip()
2985 shortcode = str(job.get("shortcode") or "").strip()
2986 url = str(job.get("url") or job.get("application_url") or "").strip()
2987 if not url and shortcode and slug:
2988 url = f"https://apply.workable.com/{slug}/j/{shortcode}/"
2989 items.append(_ats_item(
2990 provider=ATS_PROVIDER_WORKABLE,
2991 slug=slug,
2992 ident=shortcode or str(job.get("id") or ""),
2993 title=str(job.get("title") or "").strip(),
2994 url=url,
2995 description=_clean_html(str(job.get("description") or "")),
2996 description_blocks=_block_text(str(job.get("description") or "")),
2997 date=published or _date_part(job.get("created_at")),
2998 posted_date_true=bool(published),
2999 department=department,
3000 location=location,
3001 ))
3002 return items
3003
3004
3005 def parse_smartrecruiters_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:
3006 content = payload.get("content") if isinstance(payload, dict) else []
3007 if not isinstance(content, list):
3008 return []
3009 items: list[dict[str, Any]] = []
3010 for job in content:
3011 if not isinstance(job, dict):
3012 continue
3013 department = ""
3014 if isinstance(job.get("department"), dict):
3015 department = str(job["department"].get("label") or "").strip()
3016 location = ""
3017 if isinstance(job.get("location"), dict):
3018 location = _join_parts(
3019 str(job["location"].get("city") or ""),
3020 str(job["location"].get("country") or ""),
3021 )
3022 ident = str(job.get("id") or job.get("uuid") or "").strip()
3023 url = ""
3024 if isinstance(job.get("ref"), str):
3025 url = job["ref"]
3026 if not url and slug and ident:
3027 url = f"https://jobs.smartrecruiters.com/{slug}/{ident}"
3028 items.append(_ats_item(
3029 provider=ATS_PROVIDER_SMARTRECRUITERS,
3030 slug=slug,
3031 ident=ident,
3032 title=str(job.get("name") or "").strip(),
3033 url=url,
3034 description="",
3035 date=_date_part(job.get("releasedDate") or job.get("createdOn")),
3036 posted_date_true=bool(_date_part(job.get("releasedDate"))),
3037 company_name=(
3038 str(job["company"].get("name") or "").strip()
3039 if isinstance(job.get("company"), dict) else ""
3040 ),
3041 department=department,
3042 location=location,
3043 ))
3044 return items
3045
3046
3047 # --------------------------------------------------------------------------- #
3048 # Tier 2: JSON-LD JobPosting crawler
3049 # --------------------------------------------------------------------------- #
3050
3051
3052 def extract_jsonld_jobs(html: str, base_url: str = "") -> list[dict[str, Any]]:
3053 """Extract schema.org JobPosting objects embedded as JSON-LD in a page."""
3054 if not html:
3055 return []
3056 domain = _domain(base_url)
3057 items: list[dict[str, Any]] = []
3058 seen: set[str] = set()
3059 for block in extract_jsonld_blocks(html):
3060 for obj in _walk_jsonld(block):
3061 if not isinstance(obj, dict):
3062 continue
3063 if not _is_job_posting(obj):
3064 continue
3065 title = str(obj.get("title") or obj.get("name") or "").strip()
3066 if not title or title in seen:
3067 continue
3068 seen.add(title)
3069 posting_url = str(obj.get("url") or "").strip()
3070 items.append({
3071 "id": f"JL{len(items) + 1}",
3072 "title": title,
3073 "url": posting_url,
3074 "description": _clean_html(str(obj.get("description") or ""))[:2000],
3075 "date": _date_part(obj.get("datePosted")),
3076 "date_confidence": "high" if obj.get("datePosted") else "low",
3077 "provider": "careers-jsonld",
3078 "department": str(obj.get("occupationalCategory") or "").strip(),
3079 "location": _jsonld_location(obj),
3080 "source_url": base_url,
3081 "source_domain": domain,
3082 "relevance": 0.6,
3083 "why_relevant": "JobPosting structured data on careers page",
3084 })
3085 return items
3086
3087
3088 def role_page_text(
3089 url: str, *, timeout: float, deadline_monotonic: float, landed: list | None = None,
3090 redirect_guard: Callable[[str], bool] | None = None,
3091 max_bytes: int | None = None,
3092 ) -> str | None:
3093 """A role or sitemap page as text, or None when it is not text the lane
3094 can decode (a gzip sitemap, a page in another encoding): one such page
3095 costs its own role, not the whole read."""
3096 if not board_detect.is_safe_public_url(url):
3097 return None
3098 try:
3099 return http.get_text(
3100 url, accept="text/html,application/xml,*/*", timeout=timeout, retries=1,
3101 deadline_monotonic=deadline_monotonic, landed=landed, public_only=True,
3102 max_bytes=max_bytes if max_bytes is not None else board_detect.MAX_HTML_BYTES,
3103 **({"redirect_guard": redirect_guard} if redirect_guard is not None else {}),
3104 )
3105 except UnicodeDecodeError:
3106 return None
3107
3108
3109 def jsonld_role_text(html: Any) -> tuple[str, str] | None:
3110 """The text of the first ``JobPosting`` a role's page carries, with its
3111 breaks kept and as one line, or None when the page has none."""
3112 if not isinstance(html, str):
3113 return None
3114 for block in extract_jsonld_blocks(html):
3115 for obj in _walk_jsonld(block):
3116 if isinstance(obj, dict) and _is_job_posting(obj):
3117 text = str(obj.get("description") or "")
3118 if text.strip():
3119 text = unescape(text)
3120 return _block_text(text), _clean_html(text)
3121 return None
3122
3123
3124 def _walk_jsonld(block: str) -> list[Any]:
3125 try:
3126 data = json.loads(block.strip())
3127 except (json.JSONDecodeError, ValueError, RecursionError):
3128 return []
3129 out: list[Any] = []
3130 stack = [data]
3131 while stack:
3132 node = stack.pop()
3133 if isinstance(node, list):
3134 stack.extend(node)
3135 elif isinstance(node, dict):
3136 out.append(node)
3137 graph = node.get("@graph")
3138 if isinstance(graph, list):
3139 stack.extend(graph)
3140 return out
3141
3142
3143 def _is_job_posting(obj: dict[str, Any]) -> bool:
3144 type_field = obj.get("@type")
3145 if isinstance(type_field, str):
3146 return type_field.lower() == "jobposting"
3147 if isinstance(type_field, list):
3148 return any(isinstance(t, str) and t.lower() == "jobposting" for t in type_field)
3149 return False
3150
3151
3152 def _jsonld_location(obj: dict[str, Any]) -> str:
3153 loc = obj.get("jobLocation")
3154 if isinstance(loc, list):
3155 loc = loc[0] if loc else None
3156 if isinstance(loc, dict):
3157 address = loc.get("address")
3158 if isinstance(address, dict):
3159 return _join_parts(
3160 str(address.get("addressLocality") or ""),
3161 str(address.get("addressRegion") or ""),
3162 str(address.get("addressCountry") or ""),
3163 )
3164 if obj.get("jobLocationType"):
3165 return str(obj.get("jobLocationType")).strip()
3166 return ""
3167
3168
3169 # --------------------------------------------------------------------------- #
3170 # Tier 3: generic web search fallback
3171 # --------------------------------------------------------------------------- #
3172
3173 def search_jobs_web(
3174 company: str,
3175 date_range: tuple[str, str],
3176 config: dict[str, Any],
3177 *,
3178 backend: str = "auto",
3179 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
3180 """Fallback to the configured web search, for job postings only.
3181
3182 A result is kept when its URL is one posting on a supported board
3183 (Greenhouse, Ashby, Lever, Workable, SmartRecruiters, Workday) and that
3184 board's slug is a form of the company's name. Everything else a search
3185 for "careers jobs hiring" returns is left out: ads, a search engine's
3186 redirect links, encyclopedia and news pages, job aggregators and the
3187 company's own careers landing page are not roles.
3188 """
3189 if backend == "none":
3190 return [], {}
3191 query = f'{company} careers jobs hiring'
3192 raw_items, artifact = grounding.web_search(query, date_range, config, backend=backend)
3193 items: list[dict[str, Any]] = []
3194 for index, raw in enumerate(raw_items):
3195 if not isinstance(raw, dict):
3196 continue
3197 title = str(raw.get("title") or "").strip()
3198 url = str(raw.get("url") or "").strip()
3199 snippet = str(raw.get("snippet") or "").strip()
3200 board = _posting_board(url)
3201 if not board or not _names_overlap(board, company):
3202 continue
3203 items.append({
3204 "id": raw.get("id") or f"JW{index + 1}",
3205 "title": title,
3206 "url": url,
3207 "description": snippet,
3208 "date": raw.get("date"),
3209 "date_confidence": raw.get("date_confidence") or "low",
3210 "provider": "web",
3211 "source_domain": raw.get("source_domain"),
3212 "relevance": raw.get("relevance", 0.45),
3213 "why_relevant": "Job posting on a supported board, found by web search",
3214 })
3215 artifact = dict(artifact or {})
3216 artifact.update({"label": "jobs-web", "company": company, "resultCount": len(items)})
3217 return items, artifact
3218
3219
3220 # --------------------------------------------------------------------------- #
3221 # Item builders + helpers
3222 # --------------------------------------------------------------------------- #
3223
3224 def _ats_item(
3225 *,
3226 provider: str,
3227 slug: str,
3228 ident: str,
3229 title: str,
3230 url: str,
3231 description: str,
3232 date: str | None,
3233 department: str,
3234 location: str,
3235 description_blocks: str = "",
3236 posted_date_true: bool = False,
3237 company_name: str = "",
3238 whole_posting: bool = False,
3239 ) -> dict[str, Any]:
3240 """Build one board row.
3241
3242 ``description_blocks`` is the description with its paragraph and list
3243 breaks kept, ``posted_date_true`` says ``date`` is the day the role was
3244 first posted, and ``company_name`` is the company the board says it
3245 belongs to, when the provider states one. ``whole_posting`` says the row
3246 is one posting with all its locations, so another row with the same title
3247 is a different posting.
3248 """
3249 prefix = {
3250 ATS_PROVIDER_ASHBY: "AB",
3251 ATS_PROVIDER_LEVER: "LV",
3252 ATS_PROVIDER_WORKABLE: "WK",
3253 ATS_PROVIDER_SMARTRECRUITERS: "SR",
3254 ATS_PROVIDER_WORKDAY: "WD",
3255 COMPANY_PROVIDER_APPLE: "AP",
3256 COMPANY_PROVIDER_AMAZON: "AZ",
3257 COMPANY_PROVIDER_EIGHTFOLD: "EF",
3258 COMPANY_PROVIDER_GOOGLE: "GG",
3259 COMPANY_PROVIDER_IBM: "IB",
3260 PLATFORM_PROVIDER_ORACLE: "OR",
3261 PLATFORM_PROVIDER_JIBE: "JB",
3262 PLATFORM_PROVIDER_PHENOM: "PH",
3263 PLATFORM_PROVIDER_TALENTBREW: "TB",
3264 PLATFORM_PROVIDER_KULA: "KL",
3265 SITEMAP_PROVIDER: "SM",
3266 }.get(provider, "AT")
3267 return {
3268 "id": f"{prefix}{ident or slug}",
3269 "title": title,
3270 "url": url,
3271 "description": description,
3272 "description_blocks": description_blocks,
3273 "date": date,
3274 "date_confidence": "high" if date else "low",
3275 "posted_date_true": posted_date_true,
3276 "company_name": company_name,
3277 "whole_posting": whole_posting,
3278 "provider": provider,
3279 "board_token": slug,
3280 "department": department,
3281 "departments": [department] if department else [],
3282 "location": location,
3283 "offices": [location] if location else [],
3284 "relevance": 0.75,
3285 "why_relevant": f"Public {provider} job posting",
3286 }
3287
3288
3289 def _greenhouse_job_to_item(job: dict[str, Any], board_token: str) -> dict[str, Any]:
3290 departments = [
3291 str(dept.get("name") or "").strip()
3292 for dept in (job.get("departments") or [])
3293 if isinstance(dept, dict) and str(dept.get("name") or "").strip()
3294 ]
3295 offices = [
3296 str(office.get("name") or office.get("location") or "").strip()
3297 for office in (job.get("offices") or [])
3298 if isinstance(office, dict) and str(office.get("name") or office.get("location") or "").strip()
3299 ]
3300 location = ""
3301 if isinstance(job.get("location"), dict):
3302 location = str(job["location"].get("name") or "").strip()
3303 description = _clean_html(str(job.get("content") or ""))
3304 # ``updated_at`` moves on every edit, so only ``first_published`` says when
3305 # a role was posted.
3306 published = _date_part(job.get("first_published"))
3307 return {
3308 "id": f"GH{job.get('id') or job.get('internal_job_id') or board_token}",
3309 "title": str(job.get("title") or "").strip(),
3310 "url": str(job.get("absolute_url") or "").strip(),
3311 "description": description,
3312 "description_blocks": _block_text(str(job.get("content") or "")),
3313 "date": published,
3314 "date_confidence": "high" if published else "low",
3315 "posted_date_true": bool(published),
3316 "company_name": str(job.get("company_name") or "").strip(),
3317 "provider": ATS_PROVIDER_GREENHOUSE,
3318 "board_token": board_token,
3319 "department": departments[0] if departments else "",
3320 "departments": departments,
3321 "location": location,
3322 "offices": offices,
3323 "relevance": 0.75,
3324 "why_relevant": "Public Greenhouse job posting",
3325 }
3326
3327
3328 def _artifact(
3329 label: str,
3330 company: str,
3331 attempted: list[str],
3332 items: list[dict[str, Any]],
3333 explicit: bool,
3334 *,
3335 tier: str,
3336 provider: str = "",
3337 slug: str = "",
3338 ) -> dict[str, Any]:
3339 return {
3340 "label": label,
3341 "company": company,
3342 "attempted": attempted,
3343 "resultCount": len(items),
3344 "explicit": explicit,
3345 "tier": tier,
3346 "provider": provider,
3347 "board_token": slug,
3348 }
3349
3350
3351 def _candidate_slugs(company: str) -> list[str]:
3352 base = _company_slug(company)
3353 if not base:
3354 return []
3355 candidates = [base]
3356 compact = re.sub(r"(inc|labs|ai|hq|app|tech)$", "", base)
3357 if compact and compact != base:
3358 candidates.append(compact)
3359 # hyphenated form (e.g. "listen labs" -> "listen-labs")
3360 hyphen = re.sub(r"[^a-z0-9]+", "-", company.lower()).strip("-")
3361 if hyphen and hyphen not in candidates:
3362 candidates.append(hyphen)
3363 deduped: list[str] = []
3364 for token in candidates:
3365 if token and token not in deduped:
3366 deduped.append(token)
3367 return deduped[:4]
3368
3369
3370 def _join_parts(*parts: str) -> str:
3371 """Join non-empty, stripped location parts as 'City, Country'."""
3372 return ", ".join(part.strip() for part in parts if part and part.strip())
3373
3374
3375 def _company_slug(company: str) -> str:
3376 text = company.lower()
3377 text = re.sub(r"\b(inc|inc\.|llc|ltd|corp|corporation|company|co\.)\b", "", text)
3378 return re.sub(r"[^a-z0-9]+", "", text).strip()
3379
3380
3381 def _domain(url: str) -> str:
3382 return _host(url).removeprefix("www.")
3383
3384
3385 def _date_part(value: Any) -> str | None:
3386 text = str(value or "")
3387 if not text:
3388 return None
3389 match = re.search(r"\d{4}-\d{2}-\d{2}", text)
3390 return match.group(0) if match else None
3391
3392
3393 def _epoch_ms_to_date(value: Any) -> str | None:
3394 try:
3395 ms = int(value)
3396 except (TypeError, ValueError):
3397 return None
3398 if ms <= 0:
3399 return None
3400 return dates.timestamp_to_date(ms / 1000)
3401
3402
3403 def _clean_html(value: str) -> str:
3404 value = unescape(value)
3405 value = re.sub(r"<br\s*/?>", "\n", value, flags=re.I)
3406 value = re.sub(r"</p\s*>", "\n", value, flags=re.I)
3407 value = re.sub(r"<[^<>]+>", " ", value)
3408 value = re.sub(r"\s+", " ", value)
3409 return value.strip()
3410
3411
3412 _BLOCK_END = re.compile(r"<(?:br|/p|/li|/div|/h[1-6]|/tr|/ul|/ol)\b[^<>]*>", re.I)
3413
3414
3415 def _block_text(value: str) -> str:
3416 """Like ``_clean_html``, but each paragraph, heading and list item keeps its own line."""
3417 value = _BLOCK_END.sub("\n", unescape(value))
3418 value = re.sub(r"<[^<>]+>", " ", value)
3419 lines = (" ".join(line.split()) for line in value.splitlines())
3420 return "\n".join(line for line in lines if line)
3421
3422
3423 def _looks_like_careers_html(html: str) -> bool:
3424 lowered = html.lower()
3425 if any(token in lowered for token in (
3426 "ashbyhq.com", "greenhouse.io", "lever.co", "workable.com", "smartrecruiters.com",
3427 "myworkdayjobs.com", "oraclecloud.com/hcmui", "/hcmui/candidateexperience",
3428 "phenompeople", "tbcdn.talentbrew.com", "jibecdn.com", "eightfold",
3429 )):
3430 return True
3431 return bool(re.search(r"\b(open roles|open positions|join (our|the) team|current openings|jobposting)\b", lowered))
3432
3433
3434 class BoardShapeError(ValueError):
3435 """A company board answered, but not in the shape its reader expects."""
3436
3437
3438 def _read_newest_first(
3439 page: Callable[[int], Callable[[float], Any]],
3440 parse: Callable[[Any], tuple[list[dict[str, Any]], int]],
3441 *,
3442 page_size: int,
3443 row_ceiling: int,
3444 window_start: str | None,
3445 deadline: float,
3446 workers: int = COMPANY_BOARD_MAX_WORKERS,
3447 newest_first: bool = True,
3448 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
3449 """Read a board's pages, newest first, ``workers`` at a time.
3450
3451 ``page(offset)`` makes one listing call and ``parse(payload)`` returns its
3452 rows and the total the board reports, raising ``BoardShapeError`` for an
3453 answer it cannot read. The first page gives the total; every page after
3454 it up to ``row_ceiling`` is then asked, a bounded number at once, so a
3455 board of a few thousand rows is read whole inside the budget. Reading
3456 stops at the board's end, at the ceiling, at the deadline, or at a page
3457 that fails or comes back empty: no page after a failed one is asked, and
3458 the rows read before it are kept in board order.
3459
3460 A first page that fails or cannot be read, or that is empty while the
3461 board reports roles, returns no rows: the board cannot be read.
3462
3463 ``newest_first`` off is for a board that cannot be sorted by date: its
3464 rows are the whole board or a part of it, never the newest ones.
3465 """
3466 clock = _clock()
3467 info: dict[str, Any] = {
3468 "board_total": 0, "board_capped": False, "board_cut_short": False,
3469 "board_newest_first": newest_first, "board_window_covered": False,
3470 "board_row_ceiling": row_ceiling, "board_reports_total": True,
3471 }
3472 first, unanswered = _run_first_page(page(0), deadline, clock)
3473 if first is None or first is _OUT_OF_TIME:
3474 # No answer, an overload or a rate limit is not the board refusing
3475 # to be read: the run says it did not answer, and a retry may.
3476 info["board_unanswered"] = unanswered
3477 return [], info
3478 try:
3479 items, total = parse(first)
3480 except BoardShapeError:
3481 return [], info
3482 info["board_total"] = max(total, len(items))
3483 if not items:
3484 return [], info
3485 limit = min(info["board_total"], row_ceiling)
3486 calls = [page(offset) for offset in range(page_size, limit, page_size)]
3487 rest = _paged_run(calls, parse, deadline, clock, workers=workers)
3488 pages = [list(items), *rest]
3489 for rows in rest:
3490 items.extend(rows)
3491 # Every page up to the ceiling answered: a board that lost a role or two
3492 # while it was read is still read whole.
3493 every_page = len(rest) == len(calls)
3494 # Newest first, a row older than the window means the window was read
3495 # whole; in any other order only the whole board covers it.
3496 # Only rows reached through full pages count: a page that served fewer
3497 # rows than asked for leaves a gap the offsets skip, and a role posted in
3498 # the window may sit in it.
3499 older = False
3500 if newest_first and window_start is not None:
3501 for rows in pages:
3502 if any(str(row.get("date") or "") < window_start for row in rows if row.get("date")):
3503 older = True
3504 break
3505 if len(rows) < page_size:
3506 break
3507 # A board that serves fewer rows a page than asked for (a server-side cap)
3508 # answers every page and still leaves rows unread: whole only when the
3509 # rows read come to the total, give or take the drift of a live board.
3510 drift = max(2, info["board_total"] // 100)
3511 whole = (
3512 every_page and info["board_total"] <= row_ceiling
3513 and len(items) >= info["board_total"] - drift
3514 )
3515 info["board_window_covered"] = older or whole or len(items) >= info["board_total"]
3516 info["board_cut_short"] = not whole and len(items) < info["board_total"]
3517 info["board_capped"] = info["board_total"] > row_ceiling
3518 return items[:row_ceiling], info
3519
3520
3521 _STOPPED = object()
3522
3523
3524 def _paged_run(
3525 calls: list[Callable[[float], Any]],
3526 parse: Callable[[Any], tuple[list[dict[str, Any]], int]],
3527 deadline: float,
3528 clock: Callable[[], float],
3529 *,
3530 workers: int,
3531 ) -> list[list[dict[str, Any]]]:
3532 """Run listing calls at most ``workers`` at once and return the rows of
3533 each page in order, up to the first page that failed, could not be read,
3534 came back empty or would start after the deadline. Once one has, no later
3535 call that has not started yet is made; an earlier one still is, so the
3536 pages before the failed one are all read."""
3537 lock = threading.Lock()
3538 first_bad = [len(calls)]
3539
3540 def mark(index: int) -> None:
3541 with lock:
3542 first_bad[0] = min(first_bad[0], index)
3543
3544 def run(index: int, call: Callable[[float], Any]) -> Any:
3545 if index > first_bad[0]:
3546 return _STOPPED
3547 remaining = deadline - clock()
3548 if remaining <= 0:
3549 mark(index)
3550 return _OUT_OF_TIME
3551 try:
3552 payload = call(time.monotonic() + min(remaining, _request_seconds(API_TIMEOUT_SECONDS, 2)))
3553 except http.HTTPError:
3554 mark(index)
3555 return None
3556 try:
3557 rows = parse(payload)[0] if payload is not None else []
3558 except BoardShapeError:
3559 rows = []
3560 if not rows:
3561 mark(index)
3562 return rows
3563
3564 if not calls:
3565 return []
3566 pages: list[list[dict[str, Any]]] = []
3567 with ThreadPoolExecutor(max_workers=max(1, min(workers, len(calls)))) as executor:
3568 futures = [
3569 http.submit_with_context(executor, run, index, call)
3570 for index, call in enumerate(calls)
3571 ]
3572 for future in futures:
3573 rows = future.result()
3574 if not isinstance(rows, list) or not rows:
3575 break
3576 pages.append(rows)
3577 return pages
3578
3579
3580 def _safe_board_path_url(board: str, raw_path: Any) -> str:
3581 """Resolve a remote relative path against ``https://{board}/`` only when it
3582 stays strictly on ``https://{board}`` with no port/userinfo/authority smuggling."""
3583 if not isinstance(raw_path, str):
3584 return ""
3585 path = raw_path.strip()
3586 if (
3587 not path
3588 or not path.startswith("/")
3589 or path.startswith("//")
3590 or "\\" in path
3591 or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in path)
3592 ):
3593 return ""
3594 clean_board = (board or "").strip().rstrip(".").lower()
3595 if not clean_board:
3596 return ""
3597 candidate = urljoin(f"https://{clean_board}/", path)
3598 try:
3599 parsed = urlparse(candidate)
3600 port = parsed.port
3601 except ValueError:
3602 return ""
3603 if (
3604 parsed.scheme.lower() != "https"
3605 or parsed.username is not None
3606 or parsed.password is not None
3607 or port is not None
3608 or (parsed.hostname or "").rstrip(".").lower() != clean_board
3609 ):
3610 return ""
3611 return candidate
3612
3613
3614 # Amazon: one search endpoint, 100 roles per call with their full text. Errors
3615 # arrive as HTTP 200 with an ``error`` key.
3616
3617
3618 def parse_amazon_response(payload: Any) -> tuple[list[dict[str, Any]], int]:
3619 """Rows and reported hits from one ``amazon.jobs`` search page."""
3620 if not isinstance(payload, dict):
3621 raise BoardShapeError("not a JSON object")
3622 if payload.get("error"):
3623 raise BoardShapeError(str(payload["error"])[:120])
3624 jobs_list = payload.get("jobs")
3625 if not isinstance(jobs_list, list):
3626 raise BoardShapeError("no jobs list")
3627 items: list[dict[str, Any]] = []
3628 for job in jobs_list:
3629 if not isinstance(job, dict) or not job.get("title") or not job.get("job_path"):
3630 continue
3631 url = _safe_board_path_url("www.amazon.jobs", job.get("job_path"))
3632 if not url:
3633 continue
3634 text = "<br/>".join(
3635 str(job.get(key) or "")
3636 for key in ("description", "basic_qualifications", "preferred_qualifications")
3637 if job.get(key)
3638 )
3639 posted = _amazon_date(job.get("posted_date"))
3640 items.append(_ats_item(
3641 provider=COMPANY_PROVIDER_AMAZON,
3642 slug="www.amazon.jobs",
3643 ident=str(job.get("id_icims") or job.get("id") or ""),
3644 title=str(job["title"]).strip(),
3645 url=url,
3646 description=_clean_html(text),
3647 description_blocks=_block_text(text),
3648 date=posted,
3649 posted_date_true=bool(posted),
3650 department=str(job.get("business_category") or "").strip(),
3651 location=str(job.get("normalized_location") or job.get("location") or "").strip(),
3652 company_name=str(job.get("company_name") or "").strip(),
3653 whole_posting=True,
3654 ))
3655 return items, _reported_total(payload, "hits")
3656
3657
3658 def _amazon_date(value: Any) -> str | None:
3659 """``November 14, 2026`` as ``2026-11-14``."""
3660 try:
3661 return time.strftime("%Y-%m-%d", time.strptime(str(value or "").strip(), "%B %d, %Y"))
3662 except ValueError:
3663 return None
3664
3665
3666 def _amazon_url(entry: dict[str, Any]) -> str:
3667 return f"https://{entry.get('board') or 'www.amazon.jobs'}/en/search.json"
3668
3669
3670 def _amazon_params(offset: int, base_query: str = "") -> dict[str, str]:
3671 params = {"sort": "recent", "result_limit": str(AMAZON_PAGE_SIZE), "offset": str(offset)}
3672 if base_query:
3673 params["base_query"] = base_query
3674 return params
3675
3676
3677 def search_amazon_story(
3678 entry: dict[str, Any], term: str, *, deadline_monotonic: float,
3679 ) -> list[dict[str, Any]]:
3680 """The roles Amazon's search finds for a story term (``base_query``)."""
3681 url = _amazon_url(entry)
3682 if not board_detect.is_safe_public_url(url):
3683 raise http.HTTPError("Refused non-public URL")
3684 payload = http.get(
3685 url, params=_amazon_params(0, term),
3686 timeout=STORY_TIMEOUT_SECONDS, retries=1, deadline_monotonic=deadline_monotonic,
3687 public_only=True, redirect_guard=board_detect.same_site_redirect_guard(url),
3688 )
3689 return parse_amazon_response(payload)[0]
3690
3691
3692 def read_amazon_board(
3693 entry: dict[str, str], *, deadline: float, date_range: tuple[str, str],
3694 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
3695 """Amazon's roles, newest first, with the board's reported total."""
3696 url = _amazon_url(entry)
3697
3698 def page(offset: int) -> Callable[[float], Any]:
3699 params = _amazon_params(offset)
3700
3701 def fetch(http_deadline: float) -> Any:
3702 if not board_detect.is_safe_public_url(url):
3703 raise http.HTTPError("Refused non-public URL")
3704 return http.get(
3705 url, params=params, timeout=API_TIMEOUT_SECONDS, retries=2,
3706 deadline_monotonic=http_deadline, public_only=True,
3707 redirect_guard=board_detect.same_site_redirect_guard(url),
3708 )
3709
3710 return fetch
3711
3712 items, info = _read_newest_first(
3713 page, parse_amazon_response, page_size=AMAZON_PAGE_SIZE,
3714 row_ceiling=COMPANY_BOARD_ROW_CEILING, window_start=date_range[0], deadline=deadline,
3715 )
3716 # The search stops counting at 10,000, so that total is a floor.
3717 info["board_total_floor"] = info["board_total"] >= AMAZON_HITS_CAP
3718 return items, info
3719
3720
3721 # Apple: a JSON search API, 20 rows per call with a short summary, one row per
3722 # role and location, and a JSON details call per role with the full text.
3723
3724 _APPLE_SEARCH_URL = "https://jobs.apple.com/api/v1/search"
3725 _APPLE_DETAILS_URL = "https://jobs.apple.com/api/v1/jobDetails/{position}?locale=en-us"
3726
3727
3728 def _apple_search_body(page: int, query: str = "") -> dict[str, Any]:
3729 # Without the ``format`` key the API answers 200 with no results.
3730 return {
3731 "query": query,
3732 "filters": {"range": {"standardWeeklyHours": {"start": None, "end": None}}},
3733 "page": page,
3734 "locale": "en-us",
3735 "sort": "newest",
3736 "format": {"longDate": "MMMM D, YYYY", "mediumDate": "MMM D, YYYY"},
3737 }
3738
3739
3740 def parse_apple_response(payload: Any) -> tuple[list[dict[str, Any]], int]:
3741 """Rows and the reported total from one Apple search page.
3742
3743 A pipeline role (a standing requisition, flagged as managed or typed
3744 ``PIPE``) carries the day of the request as its posting date, so its date
3745 is not a true posted date. Managed pipeline roles and retail store roles
3746 (by team code or team name) are marked ``digest_excluded``.
3747 """
3748 res = payload.get("res") if isinstance(payload, dict) else None
3749 results = res.get("searchResults") if isinstance(res, dict) else None
3750 if not isinstance(results, list) or "totalRecords" not in res:
3751 raise BoardShapeError("no searchResults or totalRecords")
3752 items: list[dict[str, Any]] = []
3753 for job in results:
3754 if not isinstance(job, dict) or not job.get("postingTitle") or not job.get("positionId"):
3755 continue
3756 position_id = str(job["positionId"]).strip()
3757 if not position_id:
3758 continue
3759 encoded_position = quote(position_id, safe="")
3760 team = job.get("team") if isinstance(job.get("team"), dict) else {}
3761 locations = [loc for loc in job.get("locations") or [] if isinstance(loc, dict)]
3762 slug = quote(str(job.get("transformedPostingTitle") or "role").strip() or "role", safe="-_.")
3763 # A standing requisition: flagged as managed, or typed ``PIPE``.
3764 pipeline = bool(job.get("managedPipelineRole")) or job.get("type") == "PIPE"
3765 summary = str(job.get("jobSummary") or "").strip()
3766 item = _ats_item(
3767 provider=COMPANY_PROVIDER_APPLE,
3768 slug="jobs.apple.com",
3769 ident=str(job.get("id") or position_id),
3770 title=str(job["postingTitle"]).strip(),
3771 url=f"https://jobs.apple.com/en-us/details/{encoded_position}/{slug}",
3772 description=summary,
3773 description_blocks=summary,
3774 date=_date_part(job.get("postDateInGMT")),
3775 posted_date_true=not pipeline and bool(_date_part(job.get("postDateInGMT"))),
3776 department=str(team.get("teamName") or "").strip(),
3777 location=str(locations[0].get("name") or "").strip() if locations else "",
3778 company_name="Apple",
3779 whole_posting=True,
3780 )
3781 retail = (
3782 team.get("teamCode") == APPLE_RETAIL_TEAM
3783 or str(team.get("teamName") or "").strip().lower() == "apple retail"
3784 )
3785 item["digest_excluded"] = bool(job.get("managedPipelineRole")) or retail
3786 item["detail_url"] = _APPLE_DETAILS_URL.format(position=encoded_position)
3787 items.append(item)
3788 return items, _reported_total(res, "totalRecords")
3789
3790
3791 def read_apple_board(
3792 entry: dict[str, str], *, deadline: float, date_range: tuple[str, str],
3793 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
3794 """Apple's roles, newest first, with the board's reported total."""
3795
3796 def page(offset: int) -> Callable[[float], Any]:
3797 body = _apple_search_body(offset // APPLE_PAGE_SIZE + 1)
3798 return lambda http_deadline: http.post(
3799 _APPLE_SEARCH_URL, body, headers={"Accept": "application/json"},
3800 timeout=API_TIMEOUT_SECONDS, retries=2, deadline_monotonic=http_deadline,
3801 public_only=True, redirect_guard=board_detect.same_site_redirect_guard(_APPLE_SEARCH_URL),
3802 )
3803
3804 items, info = _read_newest_first(
3805 page, parse_apple_response, page_size=APPLE_PAGE_SIZE,
3806 row_ceiling=COMPANY_BOARD_ROW_CEILING, window_start=date_range[0], deadline=deadline,
3807 )
3808 # The board's total counts rows, so the rows read are counted the same way.
3809 info["board_rows_read"] = len(items)
3810 return _one_row_per_role(items), info
3811
3812
3813 def search_apple_story(
3814 entry: dict[str, Any], term: str, *, deadline_monotonic: float,
3815 ) -> list[dict[str, Any]]:
3816 """The roles Apple's search finds for a story term, one row per role."""
3817 payload = http.post(
3818 _APPLE_SEARCH_URL, _apple_search_body(1, term), headers={"Accept": "application/json"},
3819 timeout=STORY_TIMEOUT_SECONDS, retries=1, deadline_monotonic=deadline_monotonic,
3820 public_only=True, redirect_guard=board_detect.same_site_redirect_guard(_APPLE_SEARCH_URL),
3821 )
3822 return _one_row_per_role(parse_apple_response(payload)[0])
3823
3824
3825 def _one_row_per_role(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
3826 """Apple lists a role once per location; keep one row with every location."""
3827 roles: dict[str, dict[str, Any]] = {}
3828 for item in items:
3829 kept = roles.setdefault(str(item["url"]), item)
3830 if kept is not item:
3831 kept["offices"].extend(
3832 office for office in item["offices"] if office not in kept["offices"]
3833 )
3834 for role in roles.values():
3835 # The digest names a role's places from ``locations`` when a row has it.
3836 role["locations"] = list(role["offices"])
3837 return list(roles.values())
3838
3839
3840 def parse_apple_detail(payload: Any) -> dict[str, str] | None:
3841 """The text fields of one Apple details answer, or None when it holds none."""
3842 role = payload.get("res") if isinstance(payload, dict) else None
3843 if not isinstance(role, dict):
3844 return None
3845 found = {
3846 key: str(role.get(key) or "").strip()
3847 for key in ("description", "responsibilities", "minimumQualifications", "preferredQualifications")
3848 }
3849 return found if any(found.values()) else None
3850
3851
3852 def fetch_apple_details(
3853 items: list[dict[str, Any]], *, deadline: float,
3854 ) -> tuple[int, int]:
3855 """Fill the full text of the given Apple roles from their details calls.
3856
3857 Returns the counts left unfetched: those the deadline stopped before their
3858 call started, and those whose call failed or held no role text. A role
3859 left unfetched keeps its search summary.
3860 """
3861 def call(item: dict[str, Any]) -> Callable[[float], Any]:
3862 url = str(item.get("detail_url") or "")
3863 if not board_detect.is_safe_public_url(url) or board_detect.page_host(url) != "jobs.apple.com":
3864 return lambda _http_deadline: None
3865 return lambda http_deadline: http.get(
3866 url, headers={"Accept": "application/json"},
3867 timeout=APPLE_DETAIL_TIMEOUT_SECONDS, retries=2, deadline_monotonic=http_deadline,
3868 public_only=True, redirect_guard=board_detect.same_site_redirect_guard(url),
3869 )
3870
3871 def text_of(payload: Any) -> tuple[str, str] | None:
3872 detail = parse_apple_detail(payload)
3873 if detail is None:
3874 return None
3875 blocks = [detail["description"]]
3876 for label, key in (
3877 ("Responsibilities", "responsibilities"),
3878 ("Minimum Qualifications", "minimumQualifications"),
3879 ("Preferred Qualifications", "preferredQualifications"),
3880 ):
3881 if detail[key]:
3882 blocks.append(f"{label}\n{detail[key]}")
3883 text = "\n".join(block for block in blocks if block)
3884 return text, " ".join(text.split())
3885
3886 return _fill_role_text(items, call, text_of, deadline=deadline)
3887
3888
3889 def _fill_role_text(
3890 items: list[dict[str, Any]],
3891 call: Callable[[dict[str, Any]], Callable[[float], Any]],
3892 text_of: Callable[[Any], tuple[str, str] | None],
3893 *,
3894 deadline: float,
3895 ) -> tuple[int, int]:
3896 """Make one detail call per role and store the text ``text_of`` reads.
3897
3898 ``text_of(payload)`` returns the role's text with its breaks kept and as
3899 one line, or None when the answer holds none. Returns the counts left
3900 unfetched (late, failed).
3901 """
3902 late = failed = 0
3903 for item, payload in zip(items, _workday_run([call(item) for item in items], deadline, _clock())):
3904 if payload is _OUT_OF_TIME:
3905 late += 1
3906 continue
3907 text = text_of(payload)
3908 if text is None:
3909 failed += 1
3910 continue
3911 item["description_blocks"], item["description"] = text
3912 return late, failed
3913
3914
3915 # Eightfold: hosted boards with two API generations, and a tenant has one of
3916 # them (``api`` in the registry entry). Both list 10 roles per call with no
3917 # text, and give a role's text through one more call. Neither date a row
3918 # carries is shown to be the day the role was first posted, so no row claims
3919 # one and the board prints no count of roles new in the window.
3920
3921 def parse_eightfold_response(
3922 payload: Any, entry: dict[str, str],
3923 ) -> tuple[list[dict[str, Any]], int]:
3924 """Rows and the reported total from one Eightfold listing page."""
3925 pcsx = entry.get("api") == "pcsx"
3926 body = payload.get("data") if pcsx and isinstance(payload, dict) else payload
3927 positions = body.get("positions") if isinstance(body, dict) else None
3928 if not isinstance(positions, list):
3929 raise BoardShapeError("no positions list")
3930 board, domain = entry["board"], entry["domain"]
3931 items: list[dict[str, Any]] = []
3932 for job in positions:
3933 if not isinstance(job, dict) or not job.get("id") or not job.get("name"):
3934 continue
3935 ident = str(job["id"]).strip()
3936 if not ident:
3937 continue
3938 encoded_ident = quote(ident, safe="")
3939 fallback_url = f"https://{board}/careers/job/{encoded_ident}"
3940 if pcsx:
3941 url = _safe_board_path_url(board, job.get("positionUrl")) or fallback_url
3942 query = urlencode({"position_id": ident, "domain": domain, "hl": "en"})
3943 detail = f"https://{board}/api/pcsx/position_details?{query}"
3944 else:
3945 raw_canon = str(job.get("canonicalPositionUrl") or "").strip()
3946 url = raw_canon if board_detect.is_safe_public_url(raw_canon) else fallback_url
3947 query = urlencode({"domain": domain})
3948 detail = f"https://{board}/api/apply/v2/jobs/{encoded_ident}?{query}"
3949 locations = [str(loc).strip() for loc in job.get("locations") or [] if loc]
3950 item = _ats_item(
3951 provider=COMPANY_PROVIDER_EIGHTFOLD,
3952 slug=board,
3953 ident=ident,
3954 title=str(job["name"]).strip(),
3955 url=url,
3956 description="",
3957 date=None,
3958 department=str(job.get("department") or "").strip(),
3959 location=locations[0] if locations else str(job.get("location") or "").strip(),
3960 company_name=entry.get("name", ""),
3961 whole_posting=True,
3962 )
3963 item["detail_url"] = detail
3964 items.append(item)
3965 return items, _reported_total(body, "count")
3966
3967
3968 def read_eightfold_board(
3969 entry: dict[str, str], *, deadline: float, date_range: tuple[str, str],
3970 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
3971 """An Eightfold board's newest roles, up to the row ceiling, with its total.
3972
3973 A tenant serves one of two API generations. A detected board does not say
3974 which, so ``pcsx`` is asked first and ``v2`` when ``pcsx`` gives no rows;
3975 an entry that names its ``api`` is asked on that one alone. A 403 on every
3976 generation asked reads as no rows: the board cannot be read.
3977 """
3978 if entry.get("api"):
3979 return _read_eightfold_generation(entry, deadline=deadline)
3980 items, info = _read_eightfold_generation({**entry, "api": "pcsx"}, deadline=deadline)
3981 if items or info.get("board_unanswered"):
3982 return items, info
3983 # The robots check before the read covered the first generation's
3984 # listing; the second has its own path, checked before it is asked.
3985 if board_robots.disallowed(
3986 _eightfold_listing_url(entry["board"], "v2"),
3987 deadline_monotonic=time.monotonic() + max(0.0, deadline - _clock()()),
3988 ):
3989 return items, info
3990 return _read_eightfold_generation({**entry, "api": "v2"}, deadline=deadline)
3991
3992
3993 def _eightfold_listing_url(board: str, api: str) -> str:
3994 """The listing call of an Eightfold API generation."""
3995 return f"https://{board}/api/pcsx/search" if api == "pcsx" else f"https://{board}/api/apply/v2/jobs"
3996
3997
3998 def _read_eightfold_generation(
3999 entry: dict[str, str], *, deadline: float,
4000 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
4001 url = _eightfold_listing_url(entry["board"], str(entry.get("api") or ""))
4002
4003 def page(offset: int) -> Callable[[float], Any]:
4004 params = _eightfold_params(entry, offset)
4005
4006 def fetch(http_deadline: float) -> Any:
4007 if not board_detect.is_safe_public_url(url):
4008 raise http.HTTPError("Refused non-public URL")
4009 return http.get(
4010 url, params=params, timeout=API_TIMEOUT_SECONDS, retries=2,
4011 deadline_monotonic=http_deadline, public_only=True,
4012 redirect_guard=board_detect.same_site_redirect_guard(url),
4013 )
4014
4015 return fetch
4016
4017 items, info = _read_newest_first(
4018 page, lambda payload: parse_eightfold_response(payload, entry),
4019 page_size=EIGHTFOLD_PAGE_SIZE, row_ceiling=EIGHTFOLD_ROW_CEILING,
4020 window_start=None, deadline=deadline,
4021 )
4022 # No row carries a true posted date, so the window is never counted.
4023 info["board_window_covered"] = False
4024 return items, info
4025
4026
4027 def _eightfold_params(entry: dict[str, Any], offset: int, query: str = "") -> dict[str, str]:
4028 domain = entry["domain"]
4029 if entry.get("api") == "pcsx":
4030 params = {"domain": domain, "query": query, "location": "", "sort_by": "timestamp"}
4031 else:
4032 params = {"domain": domain, "num": str(EIGHTFOLD_PAGE_SIZE), "sort_by": "timestamp"}
4033 if query:
4034 params["query"] = query
4035 return {**params, "start": str(offset)}
4036
4037
4038 def search_eightfold_story(
4039 entry: dict[str, Any], term: str, *, deadline_monotonic: float,
4040 ) -> list[dict[str, Any]]:
4041 """The roles an Eightfold board's search finds for a story term, on the
4042 API generation the entry names. An entry that names none is asked on
4043 ``pcsx``, then on ``v2`` when ``pcsx`` refuses (403 or 404), as
4044 ``read_eightfold_board`` does; that pair counts as the board's one call."""
4045 def ask(api: str) -> list[dict[str, Any]]:
4046 generation = {**entry, "api": api}
4047 url = _eightfold_listing_url(entry["board"], api)
4048 if not board_detect.is_safe_public_url(url):
4049 raise http.HTTPError("Refused non-public URL")
4050 payload = http.get(
4051 url,
4052 params=_eightfold_params(generation, 0, term),
4053 timeout=STORY_TIMEOUT_SECONDS, retries=1, deadline_monotonic=deadline_monotonic,
4054 public_only=True, redirect_guard=board_detect.same_site_redirect_guard(url),
4055 )
4056 return parse_eightfold_response(payload, generation)[0]
4057
4058 if entry.get("api"):
4059 return ask(str(entry["api"]))
4060 try:
4061 return ask("pcsx")
4062 except http.HTTPError as exc:
4063 if exc.status_code not in (403, 404):
4064 raise
4065 if board_robots.disallowed(
4066 _eightfold_listing_url(entry["board"], "v2"), deadline_monotonic=deadline_monotonic,
4067 ):
4068 return []
4069 return ask("v2")
4070
4071
4072 def fetch_eightfold_details(
4073 items: list[dict[str, Any]], *, deadline: float,
4074 ) -> tuple[int, int]:
4075 """Fill the text of the given Eightfold roles, one call each.
4076
4077 Returns the counts left unfetched (late, failed), like the other fetchers.
4078 """
4079 def call(item: dict[str, Any]) -> Callable[[float], Any]:
4080 url = str(item.get("detail_url") or "")
4081 if not board_detect.is_safe_public_url(url):
4082 return lambda _http_deadline: None
4083 return lambda http_deadline: http.get(
4084 url, timeout=API_TIMEOUT_SECONDS, retries=1,
4085 deadline_monotonic=http_deadline, public_only=True,
4086 redirect_guard=board_detect.same_site_redirect_guard(url),
4087 )
4088
4089 def text_of(payload: Any) -> tuple[str, str] | None:
4090 body = payload.get("data", payload) if isinstance(payload, dict) else None
4091 html = ""
4092 if isinstance(body, dict):
4093 html = str(body.get("jobDescription") or body.get("job_description") or "")
4094 return (_block_text(html), _clean_html(html)) if html.strip() else None
4095
4096 return _fill_role_text(items, call, text_of, deadline=deadline)
4097
4098
4099 # Readers of company-run and platform boards, by provider: given the board's
4100 # entry (from the registry or from detection) and the listing's deadline,
4101 # each returns ``(items, board_info)`` like the hosted readers. Detail
4102 # fetchers fill role text for the roles the digest selected and return how
4103 # many were left unfetched (late, failed). Both are named, and looked up
4104 # when called, so a test may stand in for one: a bare name is a function of
4105 # this module, ``module:function`` one of ``lib.job_boards``.
4106 _COMPANY_READERS: dict[str, str] = {
4107 COMPANY_PROVIDER_AMAZON: "read_amazon_board",
4108 COMPANY_PROVIDER_APPLE: "read_apple_board",
4109 COMPANY_PROVIDER_EIGHTFOLD: "read_eightfold_board",
4110 COMPANY_PROVIDER_GOOGLE: "google:read_board",
4111 COMPANY_PROVIDER_IBM: "ibm:read_board",
4112 PLATFORM_PROVIDER_ORACLE: "oracle:read_board",
4113 PLATFORM_PROVIDER_JIBE: "jibe:read_board",
4114 PLATFORM_PROVIDER_PHENOM: "phenom:read_board",
4115 PLATFORM_PROVIDER_TALENTBREW: "talentbrew:read_board",
4116 PLATFORM_PROVIDER_KULA: "kula:read_board",
4117 }
4118 _DETAIL_FETCHERS: dict[str, str] = {
4119 ATS_PROVIDER_WORKDAY: "fetch_workday_details",
4120 COMPANY_PROVIDER_APPLE: "fetch_apple_details",
4121 COMPANY_PROVIDER_EIGHTFOLD: "fetch_eightfold_details",
4122 PLATFORM_PROVIDER_ORACLE: "oracle:fetch_details",
4123 PLATFORM_PROVIDER_PHENOM: "phenom:fetch_details",
4124 PLATFORM_PROVIDER_TALENTBREW: "talentbrew:fetch_details",
4125 PLATFORM_PROVIDER_KULA: "kula:fetch_details",
4126 }
4127
4128
4129 def _named(name: str) -> Callable[..., Any]:
4130 if ":" not in name:
4131 return globals()[name]
4132 module, function = name.split(":", 1)
4133 return getattr(importlib.import_module(f"{__package__}.job_boards.{module}"), function)
4134
4135
4136 def _company_reader(provider: str) -> Callable[..., tuple[list[dict[str, Any]], dict[str, Any]]]:
4137 return _named(_COMPANY_READERS[provider])
4138
4139
4140 def _detail_fetcher(provider: str) -> Callable[..., tuple[int, int]] | None:
4141 name = _DETAIL_FETCHERS.get(provider)
4142 return _named(name) if name else None
4143
4144
4145 def _listing_url(provider: str, entry: dict[str, Any]) -> str:
4146 """The first listing call a board's reader makes, for the robots.txt check."""
4147 board = str(entry.get("board") or "")
4148 if provider == COMPANY_PROVIDER_APPLE:
4149 return _APPLE_SEARCH_URL
4150 if provider == COMPANY_PROVIDER_AMAZON:
4151 return f"https://{board or 'www.amazon.jobs'}/en/search.json"
4152 if provider == COMPANY_PROVIDER_EIGHTFOLD:
4153 # An entry that names its generation is asked on that one alone.
4154 return _eightfold_listing_url(board, str(entry.get("api") or "pcsx"))
4155 if provider == ATS_PROVIDER_WORKDAY:
4156 return workday_list_url(board)
4157 if provider in _COMPANY_READERS and ":" in _COMPANY_READERS[provider]:
4158 module = importlib.import_module(
4159 f"{__package__}.job_boards.{_COMPANY_READERS[provider].split(':', 1)[0]}"
4160 )
4161 if provider == PLATFORM_PROVIDER_PHENOM:
4162 return module.widgets_url(entry)
4163 if provider == COMPANY_PROVIDER_GOOGLE:
4164 return module.listing_url(1)
4165 if provider == COMPANY_PROVIDER_IBM:
4166 return module.listing_url()
4167 return module.listing_url(entry)
4168 return ""
4169
4169 lines PYTHON