| 1 | """Kula: a company's public careers page on ``careers.kula.ai/<slug>``. |
| 2 | |
| 3 | The page is a Next.js page: its roles are in the React Server Components |
| 4 | payload it carries (``self.__next_f.push`` chunks), each with its title, |
| 5 | team, offices and the day it was launched, which is the day its posting |
| 6 | gives as posted. The page lists every open role at once. A role's own page |
| 7 | carries a ``JobPosting`` with the role's text. Kula's API needs a key and is |
| 8 | not used. |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import json |
| 14 | import re |
| 15 | from typing import Any, Callable |
| 16 | from urllib.parse import quote, urljoin, urlparse |
| 17 | |
| 18 | from .. import http, jobs |
| 19 | from . import detect |
| 20 | from .detect import KULA_HOST, PROVIDER_KULA |
| 21 | |
| 22 | _PUSH_MARKER = "self.__next_f.push(" |
| 23 | _JOBS_KEY = '"jobs":' |
| 24 | _JSON_ARRAY_ELEM_STARTS = frozenset('0123456789-"[{tfn') |
| 25 | _MAX_DECODE_FAILURES = 16 |
| 26 | _ANCHOR_TAG_RE = re.compile(r"<a\b([^<>]*)>", re.I) |
| 27 | |
| 28 | |
| 29 | def listing_url(entry: dict[str, Any]) -> str: |
| 30 | slug = quote(str(entry["slug"]).strip("/"), safe="") |
| 31 | return f"https://{KULA_HOST}/{slug}" |
| 32 | |
| 33 | |
| 34 | def _extract_script_bodies(html: str) -> list[str]: |
| 35 | return detect.extract_script_bodies(html) |
| 36 | |
| 37 | |
| 38 | def _extract_push_chunks(text: str) -> list[str]: |
| 39 | """Iteratively extract ``self.__next_f.push([...])`` string payloads in linear time.""" |
| 40 | parts: list[str] = [] |
| 41 | decoder = json.JSONDecoder() |
| 42 | pos = 0 |
| 43 | limit = len(text) |
| 44 | failures = 0 |
| 45 | while pos < limit: |
| 46 | idx = text.find(_PUSH_MARKER, pos) |
| 47 | if idx < 0: |
| 48 | break |
| 49 | start = idx + len(_PUSH_MARKER) |
| 50 | while start < limit and text[start].isspace(): |
| 51 | start += 1 |
| 52 | if start >= limit or text[start] != "[": |
| 53 | pos = start |
| 54 | continue |
| 55 | peek = start + 1 |
| 56 | while peek < limit and text[peek].isspace(): |
| 57 | peek += 1 |
| 58 | if peek >= limit or (text[peek] != "]" and text[peek] not in _JSON_ARRAY_ELEM_STARTS): |
| 59 | pos = peek |
| 60 | continue |
| 61 | try: |
| 62 | data, end = decoder.raw_decode(text, start) |
| 63 | except json.JSONDecodeError as exc: |
| 64 | failures += 1 |
| 65 | if "Unterminated" in exc.msg or exc.pos >= limit - 1 or failures >= _MAX_DECODE_FAILURES: |
| 66 | break |
| 67 | pos = max(start + 1, exc.pos) |
| 68 | continue |
| 69 | except ValueError: |
| 70 | failures += 1 |
| 71 | if failures >= _MAX_DECODE_FAILURES: |
| 72 | break |
| 73 | pos = start + 1 |
| 74 | continue |
| 75 | except RecursionError: |
| 76 | break |
| 77 | if isinstance(data, list) and len(data) > 1 and isinstance(data[1], str): |
| 78 | parts.append(data[1]) |
| 79 | pos = end |
| 80 | return parts |
| 81 | |
| 82 | |
| 83 | def _payload(html: str) -> str: |
| 84 | """The page's RSC payload: the text of its push chunks, in order.""" |
| 85 | bounded = html[:detect.MAX_HTML_CHARS] |
| 86 | if _PUSH_MARKER not in bounded: |
| 87 | return "" |
| 88 | scripts = _extract_script_bodies(bounded) |
| 89 | if scripts: |
| 90 | parts: list[str] = [] |
| 91 | for script in scripts: |
| 92 | if _PUSH_MARKER in script: |
| 93 | parts.extend(_extract_push_chunks(script)) |
| 94 | return "".join(parts) |
| 95 | return "".join(_extract_push_chunks(bounded)) |
| 96 | |
| 97 | |
| 98 | def _find_nested_role_list(obj: Any) -> list[dict[str, Any]] | None: |
| 99 | stack = [obj] |
| 100 | while stack: |
| 101 | node = stack.pop() |
| 102 | if isinstance(node, dict): |
| 103 | candidate = node.get("jobs") |
| 104 | if isinstance(candidate, list) and all(isinstance(row, dict) for row in candidate): |
| 105 | return candidate |
| 106 | stack.extend(reversed(list(node.values()))) |
| 107 | elif isinstance(node, list): |
| 108 | stack.extend(reversed(node)) |
| 109 | return None |
| 110 | |
| 111 | |
| 112 | def _role_list(payload: str) -> list[dict[str, Any]] | None: |
| 113 | decoder = json.JSONDecoder() |
| 114 | pos = 0 |
| 115 | limit = len(payload) |
| 116 | failures = 0 |
| 117 | while pos < limit: |
| 118 | idx = payload.find(_JOBS_KEY, pos) |
| 119 | if idx < 0: |
| 120 | break |
| 121 | start = idx + len(_JOBS_KEY) |
| 122 | while start < limit and payload[start].isspace(): |
| 123 | start += 1 |
| 124 | if start >= limit or payload[start] != "[": |
| 125 | pos = start |
| 126 | continue |
| 127 | peek = start + 1 |
| 128 | while peek < limit and payload[peek].isspace(): |
| 129 | peek += 1 |
| 130 | if peek >= limit or (payload[peek] != "]" and payload[peek] not in _JSON_ARRAY_ELEM_STARTS): |
| 131 | pos = peek |
| 132 | continue |
| 133 | try: |
| 134 | rows, end = decoder.raw_decode(payload, start) |
| 135 | except json.JSONDecodeError as exc: |
| 136 | failures += 1 |
| 137 | if "Unterminated" in exc.msg or exc.pos >= limit - 1 or failures >= _MAX_DECODE_FAILURES: |
| 138 | break |
| 139 | pos = max(start + 1, exc.pos) |
| 140 | continue |
| 141 | except ValueError: |
| 142 | failures += 1 |
| 143 | if failures >= _MAX_DECODE_FAILURES: |
| 144 | break |
| 145 | pos = start + 1 |
| 146 | continue |
| 147 | except RecursionError: |
| 148 | break |
| 149 | if isinstance(rows, list): |
| 150 | if all(isinstance(row, dict) for row in rows): |
| 151 | return rows |
| 152 | nested = _find_nested_role_list(rows) |
| 153 | if nested is not None: |
| 154 | return nested |
| 155 | pos = end |
| 156 | return None |
| 157 | |
| 158 | |
| 159 | def _slugify(title: str) -> str: |
| 160 | return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") |
| 161 | |
| 162 | |
| 163 | def _role_paths(html: str, slug: str) -> dict[str, str]: |
| 164 | prefix = f"/{slug}/" |
| 165 | if not slug or prefix not in html: |
| 166 | return {} |
| 167 | path_re = re.compile(rf"^/{re.escape(slug)}/(\d+)-[^\s\"'<>]*$") |
| 168 | paths: dict[str, str] = {} |
| 169 | for match in _ANCHOR_TAG_RE.finditer(html): |
| 170 | raw_attrs = match.group(1) |
| 171 | if prefix not in raw_attrs: |
| 172 | continue |
| 173 | href = detect.parse_html_attrs(raw_attrs).get("href", "").strip() |
| 174 | if not href or "\\" in href or href.startswith("//"): |
| 175 | continue |
| 176 | matched = path_re.match(href) |
| 177 | if matched: |
| 178 | paths[matched.group(1)] = href |
| 179 | return paths |
| 180 | |
| 181 | |
| 182 | def parse_listing(html: Any, entry: dict[str, Any]) -> tuple[list[dict[str, Any]], int]: |
| 183 | if not isinstance(html, str): |
| 184 | raise jobs.BoardShapeError("no jobs list in the page payload") |
| 185 | bounded = html[:detect.MAX_HTML_CHARS] |
| 186 | rows = _role_list(_payload(bounded)) |
| 187 | if rows is None: |
| 188 | raise jobs.BoardShapeError("no jobs list in the page payload") |
| 189 | slug = str(entry["slug"]).strip("/") |
| 190 | paths = _role_paths(bounded, slug) |
| 191 | app_names = detect.extract_meta_contents(bounded, "name", "application-name") |
| 192 | company = app_names[0] if app_names else "" |
| 193 | encoded_slug = quote(slug, safe="") |
| 194 | base = f"https://{KULA_HOST}/" |
| 195 | items: list[dict[str, Any]] = [] |
| 196 | for row in rows: |
| 197 | title = " ".join(str(row.get("title") or "").split()) |
| 198 | if not title or row.get("listed") is False or row.get("on_career_page") is False: |
| 199 | continue |
| 200 | ident = str(row.get("id") or "").strip() |
| 201 | if not ident: |
| 202 | continue |
| 203 | ats = row.get("ats_job") if isinstance(row.get("ats_job"), dict) else {} |
| 204 | team = ats.get("ats_department") if isinstance(ats.get("ats_department"), dict) else {} |
| 205 | places = [ |
| 206 | str(office.get("location") or office.get("name") or "").strip() |
| 207 | for office in ats.get("offices") or [] if isinstance(office, dict) |
| 208 | ] |
| 209 | places = [place for place in places if place] |
| 210 | posted = jobs._date_part(row.get("launch_at")) |
| 211 | fallback_path = f"/{encoded_slug}/{quote(ident, safe='')}-{_slugify(title)}" |
| 212 | candidate = urljoin(base, paths.get(ident) or fallback_path) |
| 213 | parsed = urlparse(candidate) |
| 214 | if ( |
| 215 | parsed.scheme.lower() != "https" |
| 216 | or detect.page_host(candidate) != KULA_HOST |
| 217 | or parsed.port is not None |
| 218 | ): |
| 219 | candidate = f"https://{KULA_HOST}{fallback_path}" |
| 220 | item = jobs._ats_item( |
| 221 | provider=PROVIDER_KULA, |
| 222 | slug=slug, |
| 223 | ident=ident, |
| 224 | title=title, |
| 225 | url=candidate, |
| 226 | description="", |
| 227 | date=posted, |
| 228 | posted_date_true=bool(posted), |
| 229 | department=" ".join(str(team.get("name") or "").split()), |
| 230 | location=places[0] if places else "", |
| 231 | company_name=company, |
| 232 | whole_posting=True, |
| 233 | ) |
| 234 | if len(places) > 1: |
| 235 | item["locations"] = places |
| 236 | items.append(item) |
| 237 | return items, len(items) |
| 238 | |
| 239 | |
| 240 | def read_board( |
| 241 | entry: dict[str, Any], *, deadline: float, date_range: tuple[str, str], |
| 242 | ) -> tuple[list[dict[str, Any]], dict[str, Any]]: |
| 243 | """Every role the board lists, from its one page. |
| 244 | |
| 245 | A page whose payload holds no role list raises ``BoardShapeError``, so |
| 246 | the run says the board could not be read and goes on; a failed request |
| 247 | raises its ``HTTPError``, so a timeout is noted as a slow board. |
| 248 | """ |
| 249 | url = listing_url(entry) |
| 250 | if not detect.is_safe_public_url(url): |
| 251 | raise http.HTTPError("Refused non-public URL") |
| 252 | with http.tee_failures() as failures: |
| 253 | html = http.get_text( |
| 254 | url, accept="text/html,*/*", timeout=jobs.API_TIMEOUT_SECONDS, |
| 255 | retries=2, deadline_monotonic=deadline, public_only=True, |
| 256 | redirect_guard=detect.same_site_redirect_guard(url), |
| 257 | max_bytes=detect.MAX_HTML_BYTES, |
| 258 | ) |
| 259 | if html is None and failures: |
| 260 | # A timeout or HTTP error is reported as one, not as a bad page. |
| 261 | raise failures[-1] |
| 262 | items, total = parse_listing(html or "", entry) |
| 263 | return items, {"board_total": total} |
| 264 | |
| 265 | |
| 266 | def _posted_date(html: Any) -> str | None: |
| 267 | if not isinstance(html, str): |
| 268 | return None |
| 269 | for block in jobs.extract_jsonld_blocks(html): |
| 270 | for obj in jobs._walk_jsonld(block): |
| 271 | if isinstance(obj, dict) and jobs._is_job_posting(obj): |
| 272 | return jobs._date_part(obj.get("datePosted")) |
| 273 | return None |
| 274 | |
| 275 | |
| 276 | def fetch_details(items: list[dict[str, Any]], *, deadline: float) -> tuple[int, int]: |
| 277 | """Fill each role's text from the JobPosting on its page, and its posted |
| 278 | date when the listing gave none.""" |
| 279 | |
| 280 | def call(item: dict[str, Any]) -> Callable[[float], Any]: |
| 281 | url = str(item.get("url") or "") |
| 282 | if not detect.is_safe_public_url(url) or detect.page_host(url) != KULA_HOST: |
| 283 | return lambda _http_deadline: None |
| 284 | |
| 285 | def fetch(http_deadline: float) -> Any: |
| 286 | html = jobs.role_page_text( |
| 287 | url, timeout=jobs.API_TIMEOUT_SECONDS, deadline_monotonic=http_deadline, |
| 288 | redirect_guard=detect.same_site_redirect_guard(url), |
| 289 | ) |
| 290 | posted = None if item.get("date") else _posted_date(html) |
| 291 | if posted: |
| 292 | item.update(date=posted, date_confidence="high", posted_date_true=True) |
| 293 | return html |
| 294 | return fetch |
| 295 | |
| 296 | return jobs._fill_role_text(items, call, jobs.jsonld_role_text, deadline=deadline) |
| 297 |