| 1 | """Deepline client for person runs: LinkedIn profile, LinkedIn posts, and lookup. |
| 2 | |
| 3 | Calls Deepline's integration execute endpoint directly over the shared HTTP |
| 4 | layer with the user's own ``DEEPLINE_API_KEY`` (never through proxy mode): |
| 5 | |
| 6 | POST https://code.deepline.com/api/v2/integrations/{tool}/execute |
| 7 | Authorization: Bearer <key> |
| 8 | Idempotency-Key: <hash of run id, tool, and payload> |
| 9 | {"payload": {...}} |
| 10 | |
| 11 | Every call is paid, so a ``DeeplineClient`` is created once per person run and |
| 12 | holds that run's budget: at most one lookup, two profile reads, and two post |
| 13 | pages. A 402 stops every later call in the run. Failures come back as named |
| 14 | status strings, never as exceptions. |
| 15 | |
| 16 | Privacy: payloads can carry an email. The client never logs a payload, the |
| 17 | idempotency key is a hash, and email-bearing calls are marked sensitive so the |
| 18 | shared HTTP layer keeps them out of its diagnostics and fixture capture. |
| 19 | """ |
| 20 | |
| 21 | from __future__ import annotations |
| 22 | |
| 23 | import datetime |
| 24 | import hashlib |
| 25 | import json |
| 26 | import time |
| 27 | from typing import Any, Dict, List, Optional |
| 28 | |
| 29 | from . import health, http, log |
| 30 | |
| 31 | API_BASE = "https://code.deepline.com/api/v2/integrations" |
| 32 | KEY_VAR = "DEEPLINE_API_KEY" |
| 33 | |
| 34 | TOOL_PROFILE = "harvestapi_get_profile" |
| 35 | TOOL_POSTS = "harvestapi_get_profile_posts" |
| 36 | TOOL_LOOKUP = "limadata_find_person_profiles" |
| 37 | |
| 38 | # Per-run paid-call caps. |
| 39 | DEFAULT_CAPS: Dict[str, int] = {TOOL_LOOKUP: 1, TOOL_PROFILE: 2, TOOL_POSTS: 2} |
| 40 | |
| 41 | # Values the posts tool accepts for scrapePostedLimit. The upstream does not |
| 42 | # guarantee enforcement, so callers still filter posts by date themselves. |
| 43 | POSTED_LIMITS = ("1h", "24h", "week", "month", "3months", "6months", "year") |
| 44 | |
| 45 | # One attempt's ceiling, and the least time worth starting an attempt with. |
| 46 | ATTEMPT_TIMEOUT_SECONDS = 30.0 |
| 47 | MIN_ATTEMPT_SECONDS = 10.0 |
| 48 | |
| 49 | # Status strings returned in every result's "status". |
| 50 | OK = "ok" |
| 51 | AUTH_FAILED = "auth failed" |
| 52 | OUT_OF_CREDITS = "out of credits" |
| 53 | RATE_LIMITED = "rate limited" |
| 54 | TIMEOUT = "timeout" |
| 55 | ERROR = "error" |
| 56 | OVER_BUDGET = "over budget" |
| 57 | |
| 58 | _RETRYABLE = object() |
| 59 | |
| 60 | |
| 61 | def _log(msg: str) -> None: |
| 62 | log.source_log("Deepline", msg, tty_only=False) |
| 63 | |
| 64 | |
| 65 | def is_available(config: Dict[str, Any]) -> bool: |
| 66 | """The single availability check shared by the run and doctor.""" |
| 67 | return bool((config.get(KEY_VAR) or "").strip()) |
| 68 | |
| 69 | |
| 70 | def from_config(config: Dict[str, Any], run_id: str) -> Optional["DeeplineClient"]: |
| 71 | """A client for one person run, or None when no key is configured.""" |
| 72 | if not is_available(config): |
| 73 | return None |
| 74 | return DeeplineClient(config[KEY_VAR].strip(), run_id) |
| 75 | |
| 76 | |
| 77 | def idempotency_key(run_id: str, tool: str, payload: Dict[str, Any]) -> str: |
| 78 | """Stable per (run, tool, payload); a hash, so no input value leaks.""" |
| 79 | canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")) |
| 80 | digest = hashlib.sha256(f"{run_id}\x00{tool}\x00{canonical}".encode("utf-8")) |
| 81 | return f"l30d-{digest.hexdigest()[:40]}" |
| 82 | |
| 83 | |
| 84 | def _result(status: str, data: Any = None, detail: str = "") -> Dict[str, Any]: |
| 85 | return {"status": status, "data": data, "detail": detail} |
| 86 | |
| 87 | |
| 88 | class DeeplineClient: |
| 89 | """One person run's Deepline access: budget, stop rule, and call log. |
| 90 | |
| 91 | ``events`` lists ``{"tool", "status"}`` per call outcome (no inputs), so the |
| 92 | report can say what was checked. ``stopped`` holds the status that ended |
| 93 | Deepline use for the run (``"out of credits"``), else None. |
| 94 | """ |
| 95 | |
| 96 | def __init__(self, api_key: str, run_id: str, caps: Optional[Dict[str, int]] = None): |
| 97 | self.api_key = api_key |
| 98 | self.run_id = run_id |
| 99 | self.caps = dict(DEFAULT_CAPS if caps is None else caps) |
| 100 | self._calls: Dict[str, int] = {} |
| 101 | self.stopped: Optional[str] = None |
| 102 | self.events: List[Dict[str, str]] = [] |
| 103 | |
| 104 | def calls_made(self, tool: str) -> int: |
| 105 | return self._calls.get(tool, 0) |
| 106 | |
| 107 | # -- public calls --------------------------------------------------- |
| 108 | |
| 109 | def get_profile(self, url: str, *, deadline_monotonic: Optional[float]) -> Dict[str, Any]: |
| 110 | """Read a LinkedIn profile. ``data`` is ``parse_profile`` output.""" |
| 111 | return self._call(TOOL_PROFILE, {"url": url}, deadline_monotonic, parse_profile) |
| 112 | |
| 113 | def get_posts( |
| 114 | self, |
| 115 | profile_url: str, |
| 116 | *, |
| 117 | deadline_monotonic: Optional[float], |
| 118 | posted_limit: str = "year", |
| 119 | pagination_token: Optional[str] = None, |
| 120 | ) -> Dict[str, Any]: |
| 121 | """Read one page of a profile's posts. ``data`` is ``parse_posts`` output.""" |
| 122 | if posted_limit not in POSTED_LIMITS: |
| 123 | raise ValueError(f"posted_limit must be one of {POSTED_LIMITS}") |
| 124 | payload: Dict[str, Any] = {"profile": profile_url, "scrapePostedLimit": posted_limit} |
| 125 | if pagination_token: |
| 126 | payload["paginationToken"] = pagination_token |
| 127 | return self._call(TOOL_POSTS, payload, deadline_monotonic, parse_posts) |
| 128 | |
| 129 | def find_profiles( |
| 130 | self, |
| 131 | *, |
| 132 | deadline_monotonic: Optional[float], |
| 133 | full_name: Optional[str] = None, |
| 134 | company_name: Optional[str] = None, |
| 135 | company_domain: Optional[str] = None, |
| 136 | email: Optional[str] = None, |
| 137 | ) -> Dict[str, Any]: |
| 138 | """Look up profile URLs by name plus company (or email). |
| 139 | |
| 140 | ``data`` is ``parse_lookup`` output. |
| 141 | """ |
| 142 | payload = { |
| 143 | key: value.strip() |
| 144 | for key, value in ( |
| 145 | ("full_name", full_name), |
| 146 | ("company_name", company_name), |
| 147 | ("company_domain", company_domain), |
| 148 | ("email", email), |
| 149 | ) |
| 150 | if isinstance(value, str) and value.strip() |
| 151 | } |
| 152 | return self._call(TOOL_LOOKUP, payload, deadline_monotonic, parse_lookup) |
| 153 | |
| 154 | # -- transport ------------------------------------------------------ |
| 155 | |
| 156 | def _record(self, tool: str, status: str) -> None: |
| 157 | self.events.append({"tool": tool, "status": status}) |
| 158 | |
| 159 | def _finish(self, tool: str, result: Dict[str, Any], started: float) -> Dict[str, Any]: |
| 160 | self._record(tool, result["status"]) |
| 161 | _log(f"{tool}: {result['status']} ({time.monotonic() - started:.1f}s)") |
| 162 | return result |
| 163 | |
| 164 | def _call(self, tool, payload, deadline_monotonic, parse) -> Dict[str, Any]: |
| 165 | started = time.monotonic() |
| 166 | if self.stopped: |
| 167 | return self._finish(tool, _result(self.stopped, detail="Deepline stopped for this run"), started) |
| 168 | if self.calls_made(tool) >= self.caps.get(tool, 0): |
| 169 | return self._finish(tool, _result(OVER_BUDGET, detail="per-run call cap reached"), started) |
| 170 | if not self._time_for_attempt(deadline_monotonic): |
| 171 | return self._finish(tool, _result(TIMEOUT, detail="not enough time left to start"), started) |
| 172 | |
| 173 | self._calls[tool] = self.calls_made(tool) + 1 |
| 174 | headers = { |
| 175 | "Authorization": f"Bearer {self.api_key}", |
| 176 | "Content-Type": "application/json", |
| 177 | "Idempotency-Key": idempotency_key(self.run_id, tool, payload), |
| 178 | } |
| 179 | url = f"{API_BASE}/{tool}/execute" |
| 180 | sensitive = "email" in payload |
| 181 | |
| 182 | outcome: Any = None |
| 183 | for attempt in range(2): |
| 184 | if attempt and not self._time_for_attempt(deadline_monotonic): |
| 185 | break |
| 186 | outcome = self._attempt(url, payload, headers, deadline_monotonic, sensitive) |
| 187 | if not (isinstance(outcome, tuple) and outcome[0] is _RETRYABLE): |
| 188 | break |
| 189 | if isinstance(outcome, tuple) and outcome[0] is _RETRYABLE: |
| 190 | return self._finish(tool, outcome[1], started) |
| 191 | if outcome["status"] != OK: |
| 192 | return self._finish(tool, outcome, started) |
| 193 | |
| 194 | response = outcome["data"] |
| 195 | if not isinstance(response, dict) or _payload_data(response) is None: |
| 196 | return self._finish(tool, _result(ERROR, detail="unexpected response shape"), started) |
| 197 | return self._finish(tool, _result(OK, parse(response)), started) |
| 198 | |
| 199 | @staticmethod |
| 200 | def _time_for_attempt(deadline_monotonic: Optional[float]) -> bool: |
| 201 | if deadline_monotonic is None: |
| 202 | return True |
| 203 | return deadline_monotonic - time.monotonic() >= MIN_ATTEMPT_SECONDS |
| 204 | |
| 205 | def _attempt(self, url, payload, headers, deadline_monotonic, sensitive): |
| 206 | attempt_deadline = time.monotonic() + ATTEMPT_TIMEOUT_SECONDS |
| 207 | if deadline_monotonic is not None: |
| 208 | attempt_deadline = min(attempt_deadline, deadline_monotonic) |
| 209 | try: |
| 210 | response = http.request( |
| 211 | "POST", |
| 212 | url, |
| 213 | headers=dict(headers), |
| 214 | json_data={"payload": payload}, |
| 215 | timeout=ATTEMPT_TIMEOUT_SECONDS, |
| 216 | retries=1, |
| 217 | max_429_retries=1, |
| 218 | deadline_monotonic=attempt_deadline, |
| 219 | sensitive_url=sensitive, |
| 220 | ) |
| 221 | except http.HTTPError as exc: |
| 222 | return self._failure(exc) |
| 223 | return _result(OK, response) |
| 224 | |
| 225 | def _failure(self, exc: "http.HTTPError"): |
| 226 | code = exc.status_code |
| 227 | state = exc.outcome_state |
| 228 | detail = f"HTTP {code}" if code else state |
| 229 | if state == health.PAYMENT_REQUIRED or code == 402: |
| 230 | self.stopped = OUT_OF_CREDITS |
| 231 | return _result(OUT_OF_CREDITS, detail=detail) |
| 232 | if state == health.AUTH_FAILED: |
| 233 | return _result(AUTH_FAILED, detail=detail) |
| 234 | if state == health.RATE_LIMITED: |
| 235 | return _result(RATE_LIMITED, detail=detail) |
| 236 | if state == health.TIMEOUT: |
| 237 | return (_RETRYABLE, _result(TIMEOUT, detail=detail)) |
| 238 | if code is not None and 500 <= code < 600: |
| 239 | return (_RETRYABLE, _result(ERROR, detail=detail)) |
| 240 | return _result(ERROR, detail=detail) |
| 241 | |
| 242 | |
| 243 | # -- parsing ------------------------------------------------------------------ |
| 244 | |
| 245 | |
| 246 | def _payload_data(response: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| 247 | """Tool data from an execute response. |
| 248 | |
| 249 | The HTTP API puts it under ``result.data``; older envelopes used |
| 250 | ``toolResponse.rawV2`` (under ``result`` or at the top level). |
| 251 | """ |
| 252 | if response.get("status") not in (None, "completed"): |
| 253 | return None |
| 254 | result = response.get("result") |
| 255 | candidates = [] |
| 256 | if isinstance(result, dict): |
| 257 | candidates.append(result.get("data")) |
| 258 | tool_response = result.get("toolResponse") |
| 259 | if isinstance(tool_response, dict): |
| 260 | candidates.append(tool_response.get("rawV2")) |
| 261 | tool_response = response.get("toolResponse") |
| 262 | if isinstance(tool_response, dict): |
| 263 | candidates.append(tool_response.get("rawV2")) |
| 264 | for candidate in candidates: |
| 265 | if isinstance(candidate, dict): |
| 266 | return candidate |
| 267 | return None |
| 268 | |
| 269 | |
| 270 | def _text(value: Any) -> str: |
| 271 | return value.strip() if isinstance(value, str) else "" |
| 272 | |
| 273 | |
| 274 | def _date_text(value: Any) -> str: |
| 275 | if isinstance(value, dict): |
| 276 | text = _text(value.get("text")) |
| 277 | if text: |
| 278 | return text |
| 279 | parts = [str(value[k]) for k in ("month", "year") if value.get(k) not in (None, "")] |
| 280 | return " ".join(parts) |
| 281 | return _text(value) |
| 282 | |
| 283 | |
| 284 | def _role(entry: Dict[str, Any]) -> Dict[str, Any]: |
| 285 | role = { |
| 286 | "title": _text(entry.get("position") or entry.get("title")), |
| 287 | "company": _text(entry.get("companyName")), |
| 288 | "company_linkedin_url": _text(entry.get("companyLinkedinUrl")) or None, |
| 289 | "company_universal_name": _text(entry.get("companyUniversalName")) or None, |
| 290 | "start_date": _date_text(entry.get("startDate")) or None, |
| 291 | "end_date": _date_text(entry.get("endDate")) or None, |
| 292 | } |
| 293 | website = _text(entry.get("companyWebsite") or entry.get("companyWebsiteUrl")) |
| 294 | if website: |
| 295 | role["company_website"] = website |
| 296 | return role |
| 297 | |
| 298 | |
| 299 | def _roles(raw: Any) -> List[Dict[str, Any]]: |
| 300 | if not isinstance(raw, list): |
| 301 | return [] |
| 302 | return [_role(entry) for entry in raw if isinstance(entry, dict)] |
| 303 | |
| 304 | |
| 305 | def _url_list(raw: Any) -> List[str]: |
| 306 | if isinstance(raw, (str, dict)): |
| 307 | raw = [raw] |
| 308 | if not isinstance(raw, list): |
| 309 | return [] |
| 310 | urls: List[str] = [] |
| 311 | for item in raw: |
| 312 | url = _text(item.get("url") if isinstance(item, dict) else item) |
| 313 | if url and url not in urls: |
| 314 | urls.append(url) |
| 315 | return urls |
| 316 | |
| 317 | |
| 318 | def _location(raw: Any) -> str: |
| 319 | if isinstance(raw, str): |
| 320 | return raw.strip() |
| 321 | if not isinstance(raw, dict): |
| 322 | return "" |
| 323 | text = _text(raw.get("linkedinText")) |
| 324 | if text: |
| 325 | return text |
| 326 | parsed = raw.get("parsed") |
| 327 | if isinstance(parsed, dict): |
| 328 | return ", ".join(_text(parsed.get(k)) for k in ("city", "state", "country") if _text(parsed.get(k))) |
| 329 | return "" |
| 330 | |
| 331 | |
| 332 | def parse_profile(response: Dict[str, Any]) -> Dict[str, Any]: |
| 333 | """Profile facts from a ``harvestapi_get_profile`` response.""" |
| 334 | data = _payload_data(response) or {} |
| 335 | element = data.get("element") if isinstance(data.get("element"), dict) else data |
| 336 | current = _roles(element.get("currentPosition")) |
| 337 | history = _roles(element.get("experience")) |
| 338 | company_urls: List[str] = [] |
| 339 | websites = _url_list(element.get("websites")) |
| 340 | for role in current + history: |
| 341 | url = role.get("company_linkedin_url") |
| 342 | if url and url not in company_urls: |
| 343 | company_urls.append(url) |
| 344 | site = role.get("company_website") |
| 345 | if site and site not in websites: |
| 346 | websites.append(site) |
| 347 | name = " ".join(p for p in (_text(element.get("firstName")), _text(element.get("lastName"))) if p) |
| 348 | return { |
| 349 | "name": name, |
| 350 | "headline": _text(element.get("headline")), |
| 351 | "linkedin_url": _text(element.get("linkedinUrl")) or None, |
| 352 | "public_identifier": _text(element.get("publicIdentifier")) or None, |
| 353 | "about": _text(element.get("about")), |
| 354 | "location": _location(element.get("location")), |
| 355 | "current_roles": current, |
| 356 | "history": history, |
| 357 | "websites": websites, |
| 358 | "company_linkedin_urls": company_urls, |
| 359 | } |
| 360 | |
| 361 | |
| 362 | def _post_date(posted_at: Any) -> tuple[Optional[str], Optional[str], Optional[int]]: |
| 363 | """(ISO timestamp, YYYY-MM-DD, epoch ms) from a ``postedAt`` object.""" |
| 364 | if not isinstance(posted_at, dict): |
| 365 | return None, None, None |
| 366 | stamp = posted_at.get("timestamp") |
| 367 | stamp = stamp if isinstance(stamp, int) and not isinstance(stamp, bool) else None |
| 368 | iso = _text(posted_at.get("date")) or None |
| 369 | if iso is None and stamp is not None: |
| 370 | iso = datetime.datetime.fromtimestamp(stamp / 1000, tz=datetime.timezone.utc).isoformat() |
| 371 | day = None |
| 372 | if iso: |
| 373 | try: |
| 374 | day = datetime.date.fromisoformat(iso[:10]).isoformat() |
| 375 | except ValueError: |
| 376 | day = None |
| 377 | return iso, day, stamp |
| 378 | |
| 379 | |
| 380 | def parse_posts(response: Dict[str, Any]) -> Dict[str, Any]: |
| 381 | """Posts and the next-page token from a ``harvestapi_get_profile_posts`` response.""" |
| 382 | data = _payload_data(response) or {} |
| 383 | elements = data.get("elements") |
| 384 | posts: List[Dict[str, Any]] = [] |
| 385 | for element in elements if isinstance(elements, list) else []: |
| 386 | if not isinstance(element, dict): |
| 387 | continue |
| 388 | repost = element.get("repost") |
| 389 | is_reshare = bool(repost) or bool(element.get("repostedBy")) |
| 390 | text = _text(element.get("content")) |
| 391 | if not text and isinstance(repost, dict): |
| 392 | text = _text(repost.get("content")) |
| 393 | posted_at, day, stamp = _post_date(element.get("postedAt")) |
| 394 | author = element.get("author") if isinstance(element.get("author"), dict) else {} |
| 395 | engagement = element.get("engagement") if isinstance(element.get("engagement"), dict) else {} |
| 396 | posts.append({ |
| 397 | "id": str(element.get("id") or "") or None, |
| 398 | "url": _text(element.get("linkedinUrl")) or None, |
| 399 | "text": text, |
| 400 | "posted_at": posted_at, |
| 401 | "date": day, |
| 402 | "timestamp": stamp, |
| 403 | "is_reshare": is_reshare, |
| 404 | "author": _text(author.get("name")), |
| 405 | "author_url": _text(author.get("linkedinUrl")) or None, |
| 406 | "author_id": _text(author.get("publicIdentifier")) or None, |
| 407 | "engagement": { |
| 408 | key: engagement[key] |
| 409 | for key in ("likes", "comments", "shares") |
| 410 | if isinstance(engagement.get(key), int) |
| 411 | }, |
| 412 | }) |
| 413 | pagination = data.get("pagination") if isinstance(data.get("pagination"), dict) else {} |
| 414 | return {"posts": posts, "next_token": _text(pagination.get("paginationToken")) or None} |
| 415 | |
| 416 | |
| 417 | def parse_lookup(response: Dict[str, Any]) -> Dict[str, Any]: |
| 418 | """Candidate profile URLs from a ``limadata_find_person_profiles`` response.""" |
| 419 | data = _payload_data(response) or {} |
| 420 | return {key: _text(data.get(key)) or None for key in ("linkedin_url", "github_url", "x_url")} |
| 421 |