1"""Engine shared by the South African retail Actors (Checkers, Pick n Pay, Woolworths SA, Takealot, Makro).
2
3The canonical copy is sa-retail/common/retail_core.py; sa-retail/sync.sh copies it, units.py and shared/geo_core.py
4into each Actor's src/ (Apify builds each Actor folder on its own). Edit it in sa-retail/common/ only.
5
6What it does
7- Turns the input (search terms, category URLs, product URLs) into sources; each retailer's adapter knows how to
8 page through a source with the site's own JSON endpoints and how to turn the site's records into product rows.
9- Fetches through residential sessions in South Africa (Apify Proxy group RESIDENTIAL, country ZA by default).
10 Each session's exit is checked once with two IP-location services (geo_core.check_exit). A session that meets a bot
11 wall, a 403/429 or repeated network errors is retired and the request is tried again from a new address.
12- Writes one dataset row per product. Under pay-per-event each row is one `product-scraped` event; nothing else is
13 charged: failed, blocked and empty pages, retries and duplicates are free. The run stops cleanly at the buyer's
14 spending limit.
15- Saves its progress (each source's next page and the products already written) when Apify asks it to persist
16 state, migrates the run or aborts it gracefully; a resumed run continues and never writes or charges a product
17 twice.
18"""
19
20from __future__ import annotations
21
22import asyncio
23import json
24import os
25import random
26import re
27import string
28import time
29from dataclasses import dataclass, field
30from typing import Any, AsyncIterator
31from urllib.parse import quote, urlsplit
32
33from apify import Actor, Event, EventMigratingData
34from curl_cffi.requests import AsyncSession
35
36from .pricewatch import watch
37
38from .geo_core import check_exit, now_iso
39
40EVENT = "product-scraped"
41STATE_KEY = "SCRAPE-STATE"
42SUMMARY_KEY = "RUN-SUMMARY"
43DEFAULT_PROXY = {"useApifyProxy": True, "apifyProxyGroups": ["RESIDENTIAL"], "apifyProxyCountry": "ZA"}
44ACCEPT_LANGUAGE = "en-ZA,en;q=0.9,af;q=0.6"
45BLOCK_STATUSES = {401, 403, 407, 429}
46RETRY_STATUSES = {408, 425, 500, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 530}
47
48
49BLOCK_MARKERS = ("<title>just a moment...</title>", "_cf_chl_opt", "cf-chl-widget", "challenge-platform/h/",
50 "px-captcha", "captcha-delivery.com", "verify you are human", "are you a robot",
51 "<title>access denied</title>", "pardon our interruption", "errors.edgesuite.net",
52 "awswaf.com/challenge", "request unsuccessful. incapsula", "the request could not be satisfied")
53_CRED = re.compile(r"(\w+://)[^/@\s]+@")
54_SID_CHARS = string.ascii_lowercase + string.digits
55
56
57class InputError(Exception):
58 """The input cannot be used; the message says why, in words a buyer understands."""
59
60
61class FetchFailed(Exception):
62 """A request failed on every try (network errors, server errors or bot walls). `permanent`: trying again from
63 another address cannot help (for example, a region the retailer does not deliver to)."""
64
65 def __init__(self, message: str, blocked: bool = False, permanent: bool = False):
66 super().__init__(message)
67 self.blocked = blocked
68 self.permanent = permanent
69
70
71def scrub(text: str) -> str:
72 """Remove any user:password@ (proxy login) from text before it is logged or stored."""
73 return _CRED.sub(r"\1***@", str(text))
74
75
76def wire_bytes(r: Any) -> int:
77 total = 0
78 for x in [*(getattr(r, "history", None) or []), r]:
79 total += int(getattr(x, "request_size", 0) or 0) + int(getattr(x, "response_size", 0) or 0)
80 return total
81
82
83def clamp_int(v: Any, default: int, lo: int, hi: int) -> int:
84 try:
85 n = int(v)
86 except (TypeError, ValueError):
87 n = default
88 return max(lo, min(n, hi))
89
90
91def text_list(raw: Any) -> list[str]:
92 """Strings from an input list (strings or {"url": ...} objects), trimmed, de-duplicated, order kept. One string is
93 one line per item (17 Nov 2026: a string used to be read letter by letter); a single {"url": ...} object works too."""
94 out: list[str] = []
95 if isinstance(raw, str):
96 lines = [x for x in re.split(r"[\r\n]+", raw) if x.strip()]
97 if len(lines) == 1 and "," in lines[0] and all(re.match(r"(?i)\s*(https?://|www\.)", x) for x in lines[0].split(",")):
98 lines = lines[0].split(",")
99 raw = lines
100 elif isinstance(raw, dict):
101 raw = [raw]
102 for item in raw or []:
103 v = item.get("url") if isinstance(item, dict) else item
104 v = str(v or "").strip()
105 if v and v not in out:
106 out.append(v)
107 return out
108
109
110
111
112
113@dataclass
114class Source:
115 key: str
116 kind: str
117 label: str
118 params: dict[str, Any]
119 context: str = ""
120 limit: int = 100
121 base_label: str = ""
122
123 @property
124 def value(self) -> str:
125 return str(self.params.get("value") or "")
126
127
128@dataclass
129class Page:
130 items: list[dict[str, Any]]
131 next: Any = None
132 total: int | None = None
133
134
135@dataclass
136class Context:
137 key: str
138 label: str
139 data: dict[str, Any] = field(default_factory=dict)
140
141
142
143
144
145class Proxies:
146 """Proxy URLs per session: Apify Proxy (default RESIDENTIAL, ZA) on the platform; locally a residential provider
147 set in environment variables that stay on the developer's machine (GEO_LOCAL_PROXY_TEMPLATE/USER/PASS)."""
148
149 def __init__(self, proxy_input: dict[str, Any] | None):
150 self.input = proxy_input if isinstance(proxy_input, dict) and proxy_input else dict(DEFAULT_PROXY)
151 self.local = os.environ.get("GEO_LOCAL_PROXY_TEMPLATE")
152 self.cfg: Any = None
153 self.direct = False
154
155 async def init(self) -> None:
156 if self.local:
157 return
158 self.cfg = await Actor.create_proxy_configuration(actor_proxy_input=self.input)
159 if self.cfg is None:
160 self.direct = True
161
162 @property
163 def mode(self) -> str:
164 if self.local:
165 return "local residential (ZA)"
166 if self.direct:
167 return "no proxy"
168 if self.input.get("useApifyProxy"):
169 groups = ",".join(self.input.get("apifyProxyGroups") or []) or "auto"
170 return f"Apify Proxy {groups}" + (f" ({self.input.get('apifyProxyCountry')})"
171 if self.input.get("apifyProxyCountry") else "")
172 return "custom proxies"
173
174 @property
175 def expects_za(self) -> bool:
176 """Whether every session should exit in South Africa (checked once per session)."""
177 if self.local:
178 return True
179 return bool(self.input.get("useApifyProxy")) and str(self.input.get("apifyProxyCountry") or "").upper() == "ZA"
180
181 async def url(self, session_id: str) -> str | None:
182 if self.local:
183 return self.local.format(cc="za", sid=session_id, user=os.environ.get("GEO_LOCAL_PROXY_USER", ""),
184 pw=quote(os.environ.get("GEO_LOCAL_PROXY_PASS", ""), safe=""))
185 if self.cfg is None:
186 return None
187 return await self.cfg.new_url(session_id=session_id)
188
189
190@dataclass
191class Session:
192 sid: str
193 context: str
194 proxy: str | None
195 http: AsyncSession
196 number: int
197 exit: dict[str, Any] = field(default_factory=dict)
198 active: int = 0
199 requests: int = 0
200 strikes: int = 0
201 retired: bool = False
202 data: dict[str, Any] = field(default_factory=dict)
203
204 @property
205 def label(self) -> str:
206 where = ", ".join(x for x in (self.exit.get("city"), self.exit.get("network")) if x)
207 if not where:
208 where = "ZA" if self.exit.get("verified") else "unverified"
209 return f"session {self.number} ({where})"
210
211
212class SessionPool:
213 """Residential sessions per context (store or region). A session serves a few requests at once and is retired after
214 a block, two network failures in a row, or `max_requests` requests."""
215
216 def __init__(self, engine: "Engine", *, per_session: int = 3, max_sessions: int = 4, max_requests: int = 200):
217 self.engine = engine
218 self.per_session = per_session
219 self.max_sessions = max_sessions
220 self.max_requests = max_requests
221 self.sessions: dict[str, list[Session]] = {}
222 self.creating: dict[str, int] = {}
223 self.cond = asyncio.Condition()
224 self.opened = 0
225 self.rejected_exits = 0
226 self.exits: list[dict[str, Any]] = []
227 self.unverified_ok = False
228
229 def _ready(self, ctx: str) -> list[Session]:
230 return [s for s in self.sessions.get(ctx, []) if not s.retired and s.active < self.per_session]
231
232 async def acquire(self, ctx: str) -> Session:
233 while True:
234 async with self.cond:
235 ready = self._ready(ctx)
236 if ready:
237 s = min(ready, key=lambda x: (x.active, x.requests))
238 s.active += 1
239 return s
240 live = [s for s in self.sessions.get(ctx, []) if not s.retired]
241 if len(live) + self.creating.get(ctx, 0) < self.max_sessions:
242 self.creating[ctx] = self.creating.get(ctx, 0) + 1
243 else:
244 try:
245 await asyncio.wait_for(self.cond.wait(), timeout=5)
246 except asyncio.TimeoutError:
247 pass
248 continue
249 s = None
250 try:
251 s = await self._open(ctx)
252 finally:
253 async with self.cond:
254 self.creating[ctx] -= 1
255 if s is not None:
256 self.sessions.setdefault(ctx, []).append(s)
257 s.active += 1
258 self.cond.notify_all()
259 if s is not None:
260 return s
261
262 async def _open(self, ctx: str) -> Session:
263 eng = self.engine
264 attempts = 0
265 while True:
266 attempts += 1
267 sid = "sa" + "".join(random.choice(_SID_CHARS) for _ in range(12))
268 proxy = await eng.proxies.url(sid)
269 http = AsyncSession(impersonate="chrome", headers={"Accept-Language": ACCEPT_LANGUAGE})
270 exit_info: dict[str, Any] = {}
271 if proxy and eng.proxies.expects_za and not self.unverified_ok:
272 try:
273 ex, spent = await asyncio.wait_for(check_exit(http, proxy), timeout=40)
274 except Exception:
275 ex, spent = None, 0
276 eng.stats["checkBytes"] += spent
277 eng.stats["bytes"] += spent
278 if ex is None or not ex.verified or ex.country != "za":
279 self.rejected_exits += 1
280 seen = (ex.disagreement or (ex.country or "unknown").upper()) if ex is not None else "no answer"
281 Actor.log.info(f"Address not used: not confirmed in South Africa ({seen})")
282 await _close(http)
283 if attempts >= 6:
284
285 self.unverified_ok = True
286 Actor.log.warning("Could not confirm a South African address after 6 tries; continuing with "
287 "unverified residential sessions.")
288 proxy = await eng.proxies.url(sid)
289 http = AsyncSession(impersonate="chrome", headers={"Accept-Language": ACCEPT_LANGUAGE})
290 else:
291 continue
292 else:
293 exit_info = {"country": "ZA", "city": ex.city, "network": ex.network, "verified": True}
294 self.opened += 1
295 s = Session(sid=sid, context=ctx, proxy=proxy, http=http, number=self.opened, exit=exit_info)
296 try:
297 await eng.adapter.prepare_session(eng, s, eng.contexts.get(ctx))
298 except FetchFailed as e:
299 await _close(http)
300 if attempts >= 4 or e.permanent:
301 raise
302 Actor.log.info(f"Session setup failed ({e}); trying another address")
303 continue
304 if exit_info and len(self.exits) < 50:
305 self.exits.append({**exit_info, "context": ctx or "default"})
306 if exit_info:
307 Actor.log.info(f"Opened {s.label}" + (f" for {eng.contexts[ctx].label}" if ctx else ""))
308 return s
309
310 async def release(self, s: Session, *, ok: bool = False, failed: bool = False, blocked: bool = False) -> None:
311 async with self.cond:
312 s.active -= 1
313 s.requests += 1
314 if blocked:
315 s.retired = True
316 elif failed:
317 s.strikes += 1
318 if s.strikes >= 2:
319 s.retired = True
320 elif ok:
321 s.strikes = 0
322 if s.requests >= self.max_requests:
323 s.retired = True
324 if s.retired and s.active <= 0:
325 lst = self.sessions.get(s.context, [])
326 if s in lst:
327 lst.remove(s)
328 asyncio.ensure_future(_close(s.http))
329 self.cond.notify_all()
330
331 async def close(self) -> None:
332 for lst in self.sessions.values():
333 for s in lst:
334 await _close(s.http)
335 self.sessions.clear()
336
337
338async def _close(http: AsyncSession) -> None:
339 try:
340 await http.close()
341 except Exception:
342 pass
343
344
345@dataclass
346class Response:
347 status: int
348 url: str
349 headers: Any
350 content: bytes
351 elapsed: float
352
353 @property
354 def text(self) -> str:
355 return self.content.decode("utf-8", errors="replace")
356
357 def json(self) -> Any:
358 return json.loads(self.content)
359
360
361
362
363
364def track_key(r: dict[str, Any]) -> str:
365 """One product at one store or region: what price tracking compares between runs."""
366 store = r.get("store")
367 where = (store.get("key") or store.get("storeId") or store.get("name")) if isinstance(store, dict) else store
368 return f"{where or ''}|{r.get('productId') or r.get('sku') or r.get('barcode') or r.get('name')}"
369
370
371class Output:
372 """Pushes product rows. Under pay-per-event each row is one `product-scraped` event; the SDK writes only the rows
373 the buyer's spending limit covers, and `limit_reached` then stops the run."""
374
375 def __init__(self, cap: int = 0) -> None:
376 info = Actor.get_charging_manager().get_pricing_info()
377 self.paid = info.pricing_model == "PAY_PER_EVENT"
378 self.written = 0
379 self.cap = cap
380 self.cap_reached = False
381 self.limit_reached = False
382 self.lock = asyncio.Lock()
383
384 async def push(self, rows: list[dict[str, Any]]) -> int:
385 if not rows:
386 return 0
387 async with self.lock:
388 if self.limit_reached or self.cap_reached:
389 return 0
390 if self.cap:
391 room = self.cap - self.written
392 if room < len(rows):
393 rows = rows[:max(room, 0)]
394 self.cap_reached = True
395 if not rows:
396 return 0
397 keys = [track_key(r) for r in rows]
398 rows = [{**r, **watch.fields(k, r.get("price"), r.get("name"))} for r, k in zip(rows, keys)]
399 if self.paid:
400 result = await Actor.push_data(rows, charged_event_name=EVENT)
401 written = int(result.charged_count)
402 if written < len(rows) or result.event_charge_limit_reached:
403 self.limit_reached = True
404 else:
405 await Actor.push_data(rows)
406 written = len(rows)
407 watch.commit(keys[:written])
408 self.written += written
409 if self.cap and self.written >= self.cap:
410 self.cap_reached = True
411 return written
412
413
414
415
416
417class Engine:
418 def __init__(self, adapter: Any, inp: dict[str, Any]):
419 self.adapter = adapter
420 self.inp = inp
421 self.retailer = adapter.retailer
422 self.max_concurrency = clamp_int(inp.get("maxConcurrency"), adapter.default_concurrency, 1, 20)
423
424
425 self.input_notes: list[str] = []
426 total_alias = ("maxProducts", "maxResults", "maxItemsTotal", "maxTotalItems", "limit")
427 per_alias = ("maxProductsPerSearch", "maxProductsPerCategory", "maxResultsPerSearch", "maxResultsPerQuery",
428 "maxItemsPerSearch", "maxItemsPerQuery", "maxProductsPerSource", "maxItemsPerStartUrl")
429 self.max_total = self._limit("maxItems", total_alias, 0, 0, 1_000_000)
430 self.per_source = self._limit("maxItemsPerSource", per_alias, 100, 1, 100_000)
431 if (any(inp.get(a) not in (None, "") for a in total_alias) and self.max_total and self.per_source == 100
432 and not any(inp.get(a) not in (None, "") for a in per_alias)):
433 self.per_source = min(max(self.per_source, self.max_total), 100_000)
434 self.specials_only = bool(inp.get("specialsOnly", False))
435 self.proxies = Proxies(inp.get("proxyConfiguration"))
436 self.pool = SessionPool(self, per_session=adapter.per_session,
437 max_sessions=max(2, -(-self.max_concurrency // adapter.per_session) + 1))
438 self.sem = asyncio.Semaphore(self.max_concurrency)
439 self.host_slots: dict[str, float] = {}
440 self.host_pause: dict[str, float] = {}
441 self.out: Output | None = None
442 self.contexts: dict[str, Context] = {}
443 self.sources: list[Source] = []
444 self.state: dict[str, Any] = {"sources": {}, "rows": 0}
445 self.seen: set[str] = set()
446 self.stats: dict[str, Any] = {k: 0 for k in (
447 "requests", "retries", "blocked", "failedRequests", "bytes", "checkBytes", "pages", "productsSeen",
448 "duplicates", "notOnSpecial", "detailsFetched", "detailsFailed")}
449 self.source_errors: dict[str, str] = {}
450 self.source_totals: dict[str, int | None] = {}
451 self.stop_reason: str | None = None
452 self.migrating = False
453 self.saving = asyncio.Lock()
454 self.inflight_pages = 0
455 self.started = time.monotonic()
456 self.kvs: Any = None
457 self.last_status = 0.0
458 self.suspended = asyncio.Event()
459 self.test_migrate_after = int(os.environ.get("RETAIL_TEST_MIGRATE_AFTER") or 0)
460 self._test_migration = False
461
462
463
464 async def _polite(self, host: str) -> None:
465 gap = self.adapter.min_interval
466 loop = asyncio.get_running_loop()
467 now = loop.time()
468 slot = max(now, self.host_slots.get(host, 0.0), self.host_pause.get(host, 0.0))
469 self.host_slots[host] = slot + gap
470 if slot > now:
471 await asyncio.sleep(slot - now)
472
473 def pause_host(self, host: str, seconds: float) -> None:
474 loop = asyncio.get_running_loop()
475 self.host_pause[host] = max(self.host_pause.get(host, 0.0), loop.time() + seconds)
476
477 async def request(self, method: str, url: str, *, context: str = "", headers: dict[str, str] | None = None,
478 json_body: Any = None, data: Any = None, timeout: float = 45, tries: int = 4,
479 allow_404: bool = True, ok_statuses: tuple[int, ...] = (200,),
480 blocked_check: Any = None, allow_redirects: bool = True) -> Response | None:
481 """One request through a residential session, retried from new addresses on network errors, bot walls,
482 403/429 and 5xx. Returns None for 404 (when allowed); raises FetchFailed when every try failed."""
483 host = urlsplit(url).hostname or ""
484 last = "no attempt"
485 was_blocked = False
486 for attempt in range(1, tries + 1):
487 if attempt > 1:
488 self.stats["retries"] += 1
489 await asyncio.sleep(min(1.5 * attempt + random.random(), 8))
490 s = await self.pool.acquire(context if self.adapter.context_sessions else "")
491 ok = failed = blocked = False
492 try:
493 async with self.sem:
494 await self._polite(host)
495 self.stats["requests"] += 1
496 t0 = time.monotonic()
497 try:
498 r = await s.http.request(method, url, proxy=s.proxy, headers=headers, json=json_body,
499 data=data, timeout=timeout, allow_redirects=allow_redirects,
500 max_redirects=5)
501 except Exception as e:
502 failed = True
503 resp = getattr(e, "response", None)
504 if resp is not None:
505 self.stats["bytes"] += wire_bytes(resp)
506 last = scrub(f"{type(e).__name__}: {str(e).splitlines()[0][:160]}")
507 continue
508 elapsed = time.monotonic() - t0
509 self.stats["bytes"] += wire_bytes(r)
510 status = r.status_code
511 content = r.content or b""
512 head = content[:20000].decode("utf-8", errors="ignore").lower()
513 challenge = any(m in head for m in BLOCK_MARKERS) and not head.lstrip().startswith(("{", "["))
514 if blocked_check is not None and status in ok_statuses and not challenge:
515 try:
516 challenge = bool(blocked_check(status, content))
517 except Exception:
518 challenge = False
519 if status in ok_statuses and not challenge:
520 ok = True
521 return Response(status, str(r.url), r.headers, content, elapsed)
522 if status == 404 and allow_404:
523 ok = True
524 return None
525 if status in BLOCK_STATUSES or challenge:
526 blocked = was_blocked = True
527 self.stats["blocked"] += 1
528 last = f"blocked by the site (HTTP {status})"
529 if status == 429:
530 ra = r.headers.get("retry-after")
531 wait = float(ra) if ra and str(ra).strip().isdigit() else 5.0 * attempt
532 self.pause_host(host, min(wait, 60))
533 Actor.log.info(f"{host}: {last}; trying another address")
534 continue
535 if status in RETRY_STATUSES:
536 failed = True
537 last = f"HTTP {status}"
538 self.pause_host(host, 1.0 * attempt)
539 continue
540 ok = True
541 raise FetchFailed(f"HTTP {status} from {host}: {content[:160].decode('utf-8', errors='replace')}")
542 finally:
543 await self.pool.release(s, ok=ok, failed=failed, blocked=blocked)
544 self.stats["failedRequests"] += 1
545 raise FetchFailed(f"{last} (after {tries} tries)", blocked=was_blocked)
546
547 async def get_json(self, url: str, **kw: Any) -> Any:
548 r = await self.request("GET", url, **kw)
549 return None if r is None else _json(r, url)
550
551 async def post_json(self, url: str, body: Any = None, **kw: Any) -> Any:
552 r = await self.request("POST", url, json_body=body, **kw)
553 return None if r is None else _json(r, url)
554
555
556
557 def _source_state(self, src: Source) -> dict[str, Any]:
558 return self.state["sources"].setdefault(src.key, {"cursor": None, "emitted": 0, "done": False})
559
560 async def save_state(self) -> None:
561 async with self.saving:
562 self.state["rows"] = self.out.written if self.out else 0
563 self.state["seen"] = sorted(self.seen)
564 self.state["savedAt"] = now_iso()
565 await self.kvs.set_value(STATE_KEY, self.state)
566
567 async def load_state(self) -> bool:
568 raw = await self.kvs.get_value(STATE_KEY)
569 if not isinstance(raw, dict) or not isinstance(raw.get("sources"), dict):
570 return False
571 self.state = raw
572 self.seen = set(raw.get("seen") or [])
573 return True
574
575 async def reconcile(self) -> int:
576 """Rows written after the last saved state (a crash between saves) count as seen, so they are never written or
577 charged again."""
578 dataset = await Actor.open_dataset()
579 found = 0
580 async for item in dataset.iterate_items(offset=int(self.state.get("rows") or 0),
581 fields=["productId", "store"]):
582 found += 1
583 store = item.get("store") if isinstance(item.get("store"), dict) else {}
584 self.seen.add(f"{item.get('productId')}|{store.get('key') or ''}")
585 return found
586
587 async def on_persist(self, data: Any) -> None:
588 if getattr(data, "is_migrating", False):
589 await self.on_migrating(data)
590 return
591 if not self.migrating:
592 try:
593 await self.save_state()
594 except Exception as e:
595 Actor.log.warning(f"Saving progress failed: {e}")
596
597 async def on_migrating(self, _data: Any) -> None:
598 await self._suspend("The run is moving to another server: progress saved, it continues from here there")
599
600 async def on_aborting(self, _data: Any) -> None:
601 await self._suspend("The run is being aborted: progress saved, so a resurrected run continues from here")
602
603 async def _suspend(self, message: str) -> None:
604 if self.migrating:
605 return
606 self.migrating = True
607 for _ in range(60):
608 if self.inflight_pages <= 0:
609 break
610 await asyncio.sleep(0.5)
611 try:
612 await self.save_state()
613 Actor.log.info(message)
614 except Exception as e:
615 Actor.log.warning(f"Saving progress failed: {e}")
616 finally:
617 self.suspended.set()
618
619 async def _simulate_migration(self) -> None:
620 """Local test only (RETAIL_TEST_MIGRATE_AFTER=n): act as if Apify migrated the run after n products, then stop
621 the process the way a migrated container stops."""
622 Actor.log.warning(f"TEST: simulating a migration after {self.out.written if self.out else 0} products")
623 Actor.event_manager.emit(event=Event.MIGRATING, event_data=EventMigratingData())
624 await asyncio.sleep(0.2)
625 await self.suspended.wait()
626 Actor.log.warning("TEST: progress saved; the process stops now as a migrated container would")
627 os._exit(0)
628
629
630
631 def remaining(self) -> int | None:
632 if not self.max_total:
633 return None
634 return max(0, self.max_total - (self.out.written if self.out else 0))
635
636 def stop(self, reason: str) -> None:
637 if not self.stop_reason:
638 self.stop_reason = reason
639 Actor.log.info(f"Stopping: {reason}")
640
641 @property
642 def stopping(self) -> bool:
643 return bool(self.stop_reason) or self.migrating or bool(self.out and (self.out.limit_reached
644 or self.out.cap_reached))
645
646 def _key(self, row: dict[str, Any]) -> str:
647 store = row.get("store") if isinstance(row.get("store"), dict) else {}
648 return f"{row.get('productId')}|{store.get('key') or ''}"
649
650 async def run_source(self, src: Source) -> None:
651 st = self._source_state(src)
652 if st.get("done"):
653 return
654 cursor = st.get("cursor")
655 position = int(st.get("emitted") or 0)
656 empty_pages = 0
657 while not self.stopping:
658 want = src.limit - int(st.get("emitted") or 0)
659 if want <= 0:
660 break
661 rem = self.remaining()
662 if rem is not None and rem <= 0:
663 self.stop(f"the limit of {self.max_total} products was reached")
664 break
665 self.inflight_pages += 1
666 try:
667 try:
668 page = await self.adapter.fetch_page(self, src, cursor)
669 except FetchFailed as e:
670 msg = str(e)
671 self.source_errors[src.key] = msg
672 Actor.log.warning(f"{src.label}: {msg}")
673 if e.blocked:
674 self.stats.setdefault("blockedSources", 0)
675 self.stats["blockedSources"] += 1
676 break
677 self.stats["pages"] += 1
678 if page.total is not None:
679 self.source_totals[src.key] = page.total
680 rows = []
681 for item in page.items:
682 self.stats["productsSeen"] += 1
683 if self.specials_only and not on_special(item):
684 self.stats["notOnSpecial"] += 1
685 continue
686 k = self._key(item)
687 if k in self.seen:
688 self.stats["duplicates"] += 1
689 continue
690 rows.append(item)
691 take = min(want, rem) if rem is not None else want
692 rows = rows[:take]
693 if rows and self.adapter.wants_details(self, src):
694 rows = await self.adapter.enrich(self, src, rows)
695 if self.migrating:
696 break
697 stamp = now_iso()
698 for r in rows:
699 position += 1
700 r["position"] = position
701 r["sourceType"] = src.kind
702 r["sourceValue"] = src.value
703 r["scrapedAt"] = stamp
704 rows = [finish_row(self.retailer, r) for r in rows]
705 for r in rows:
706 self.seen.add(self._key(r))
707 written = await self.out.push(rows)
708 if self.test_migrate_after and not self._test_migration and self.out.written >= self.test_migrate_after:
709 self._test_migration = True
710 asyncio.ensure_future(self._simulate_migration())
711 st["emitted"] = int(st.get("emitted") or 0) + written
712 cursor = page.next
713 st["cursor"] = cursor
714 if written < len(rows):
715 for r in rows[written:]:
716 self.seen.discard(self._key(r))
717 self.stop(f"the limit of {self.max_total} products was reached" if self.out.cap_reached
718 else "the run's spending limit was reached")
719 break
720 if written:
721 empty_pages = 0
722 else:
723 empty_pages += 1
724 if empty_pages >= 25:
725
726 Actor.log.info(f"{src.label}: no new products in the last 25 pages; moving on")
727 st["done"] = True
728 break
729 if src.kind == "product" and not page.items and not st.get("emitted"):
730 self.source_errors[src.key] = "product not found on the site (removed, or a wrong URL)"
731 if cursor is None or not page.items:
732 st["done"] = True
733 break
734 finally:
735 self.inflight_pages -= 1
736 await self.status()
737 if int(st.get("emitted") or 0) >= src.limit:
738 st["done"] = True
739
740 def _limit(self, key: str, aliases: tuple[str, ...], default: int, lo: int, hi: int) -> int:
741 """Our limit, or another scraper's name for it when ours is at its default: Apify fills in the form's default
742 before the run starts, so ours at the default means the buyer did not set it."""
743 own = clamp_int(self.inp.get(key), default, lo, hi)
744 alias = next((a for a in aliases if self.inp.get(a) not in (None, "")), None)
745 if alias and own == default:
746 n = clamp_int(self.inp.get(alias), default, lo, hi)
747 if n != default:
748 self.input_notes.append(f"{alias} {n} used as {key}")
749 return n
750 return own
751
752 async def status(self, force: bool = False) -> None:
753 now = time.monotonic()
754 if not force and now - self.last_status < 10:
755 return
756 self.last_status = now
757 try:
758 await Actor.set_status_message(
759 f"{self.out.written if self.out else 0} products written from {self.stats['pages']} pages "
760 f"({len([k for k, v in self.state['sources'].items() if v.get('done')])}/{len(self.sources)} sources "
761 f"done)")
762 except Exception:
763 pass
764
765 async def run(self) -> None:
766 self.kvs = await Actor.open_key_value_store()
767 try:
768 self.contexts = {c.key: c for c in await self.adapter.contexts(self)}
769 self.sources = await self.adapter.build_sources(self)
770 except InputError as e:
771 await Actor.fail(status_message=str(e))
772 return
773 if not self.sources:
774 await Actor.fail(status_message="Nothing to scrape: give at least one search term or a "
775 f"{self.retailer} category or product URL.")
776 return
777 await self.proxies.init()
778 self.out = Output(cap=self.max_total)
779 await watch.start(self.inp, self.retailer)
780 resumed = await self.load_state()
781 if resumed:
782 n = await self.reconcile()
783 self.out.written = int(self.state.get("rows") or 0) + n
784 Actor.log.info(f"Resuming: {self.out.written} product(s) already written"
785 + (f" ({n} after the last save)" if n else ""))
786 Actor.on(Event.PERSIST_STATE, self.on_persist)
787 Actor.on(Event.MIGRATING, self.on_migrating)
788 Actor.on(Event.ABORTING, self.on_aborting)
789 Actor.log.info(f"{self.retailer}: {len(self.sources)} source(s); up to {self.per_source} products each"
790 + (f", {self.max_total} in total" if self.max_total else "")
791 + ("; specials only" if self.specials_only else "")
792 + f"; proxies: {self.proxies.mode}; {self.max_concurrency} requests at once"
793 + ("; pay per event: one product-scraped event per product row" if self.out.paid else ""))
794 try:
795 await self.adapter.setup(self)
796 except FetchFailed as e:
797 await self._finish(f"the site could not be reached: {e}", failed=True)
798 return
799 except InputError as e:
800 await Actor.fail(status_message=str(e))
801 return
802 sem = asyncio.Semaphore(self.adapter.source_parallelism)
803
804 async def one(src: Source) -> None:
805 async with sem:
806 if not self.stopping:
807 await self.run_source(src)
808
809 try:
810 await asyncio.gather(*(one(s) for s in self.sources))
811 finally:
812 await self.pool.close()
813 if self.migrating:
814 return
815 if self.out.limit_reached:
816 self.stop("the run's spending limit was reached")
817 elif self.out.cap_reached:
818 self.stop(f"the limit of {self.max_total} products was reached")
819 await self._finish(self.stop_reason)
820
821 async def _finish(self, reason: str | None, failed: bool = False) -> None:
822 written = self.out.written if self.out else 0
823 errors = len(self.source_errors)
824 secs = round(time.monotonic() - self.started, 1)
825 summary = {
826 "retailer": self.retailer,
827 "productsWritten": written,
828 "chargedEvents": written if (self.out and self.out.paid) else 0,
829 "stopReason": reason or "every source finished",
830 "sources": [
831 {"source": s.label, "context": self.contexts[s.context].label if s.context in self.contexts else None,
832 "productsWritten": int(self._source_state(s).get("emitted") or 0),
833 "resultsOnSite": self.source_totals.get(s.key), "finished": bool(self._source_state(s).get("done")),
834 "error": self.source_errors.get(s.key)} for s in self.sources],
835 "stats": {**self.stats, "approxProxyMB": round(self.stats["bytes"] / 1_048_576, 3),
836 "seconds": secs, "sessionsOpened": self.pool.opened,
837 "addressesRejected": self.pool.rejected_exits},
838 "exits": self.pool.exits,
839 "finishedAt": now_iso(),
840 "priceTracking": await watch.finish(),
841 }
842 try:
843 await self.kvs.set_value(SUMMARY_KEY, summary)
844 self.state["finished"] = True
845 await self.save_state()
846 except Exception as e:
847 Actor.log.warning(f"Saving the summary failed: {e}")
848 parts = [f"Done: {written} product(s) from {self.retailer}"]
849 if reason:
850 parts.append(f"stopped because {reason}")
851 if errors:
852 parts.append(f"{errors} source(s) failed (see the log and RUN-SUMMARY)")
853 if self.stats["duplicates"]:
854 parts.append(f"{self.stats['duplicates']} duplicate(s) skipped")
855 if self.specials_only and self.stats["notOnSpecial"]:
856 parts.append(f"{self.stats['notOnSpecial']} not on special skipped")
857 msg = "; ".join(parts) + f". {secs} s." + watch.line()
858 Actor.log.info(msg + f" Proxy traffic about {self.stats['bytes'] / 1_048_576:.2f} MB; "
859 f"{self.stats['requests']} requests, {self.stats['retries']} retries, "
860 f"{self.stats['blocked']} blocked.")
861 if written == 0 and (failed or (errors and errors >= len(self.sources))):
862 await Actor.fail(status_message=msg)
863 return
864 await Actor.set_status_message(msg, is_terminal=True)
865
866
867def _json(r: Response, url: str) -> Any:
868 try:
869 return r.json()
870 except Exception:
871 raise FetchFailed(f"the site answered with something other than JSON ({urlsplit(url).hostname}, "
872 f"{len(r.content)} bytes)") from None
873
874
875
876
877ROW_FIELDS = (
878 "retailer", "productId", "sku", "barcode", "name", "brand", "size", "sizeValue", "sizeUnit", "packCount",
879 "soldByWeight", "price", "currency", "wasPrice", "promoPrice", "onSpecial", "savings", "unitPrice",
880 "unitPriceUnit", "loyaltyPrice", "loyaltyProgram", "loyaltyValidFrom", "loyaltyValidUntil", "promotions",
881 "inStock", "stockStatus", "stockQuantity", "category", "categories", "imageUrl", "url", "rating", "reviewCount",
882 "seller", "deliveryEstimate", "store", "position", "sourceType", "sourceValue", "scrapedAt",
883)
884
885
886def on_special(r: dict[str, Any]) -> bool:
887 """On special: a was-price above the price, a promotion, or a loyalty (member) price. An adapter can decide
888 itself by setting `_onSpecial`."""
889 if r.get("_onSpecial") is not None:
890 return bool(r["_onSpecial"])
891 price, was = r.get("price"), r.get("wasPrice")
892 return bool((was is not None and price is not None and was > price) or r.get("promotions")
893 or r.get("loyaltyPrice") is not None)
894
895
896def finish_row(retailer: str, r: dict[str, Any]) -> dict[str, Any]:
897 """The row as written: every row has the same fields in the same order; retailer-specific extras follow.
898
899 Adapters may pass `_size` (a parse_size dict for a size they read from a dedicated field), `_unitPrice` and
900 `_unitPriceUnit` (the site's own unit price), `_unitPriceOk` (False for general merchandise, where a price per kg
901 or litre would be meaningless) and `_onSpecial`; keys starting with "_" are not written."""
902 from .units import parse_size, unit_price
903
904 r = dict(r)
905 r["retailer"] = retailer
906 if not r.get("currency"):
907 r["currency"] = "ZAR"
908 sz = r.get("_size") if isinstance(r.get("_size"), dict) else None
909 if sz is None and r.get("size"):
910 sz = parse_size(str(r["size"]), r.get("name"))
911 if sz is None:
912 sz = {"text": str(r["size"]), "count": None, "each": None, "unit": None, "total": None}
913 if sz is None:
914 sz = parse_size(r.get("name"))
915 r["size"] = sz.get("text") if sz else None
916 if r.get("sizeValue") is None:
917 r["sizeValue"] = sz.get("total") if sz else None
918 if r.get("sizeUnit") is None:
919 r["sizeUnit"] = sz.get("unit") if sz else None
920 if r.get("packCount") is None:
921 r["packCount"] = sz.get("count") if sz else None
922 price, was = r.get("price"), r.get("wasPrice")
923 if was is not None and (price is None or was <= price):
924 r["wasPrice"] = was = None
925 if r.get("savings") is None and was is not None and price is not None:
926 r["savings"] = round(was - price, 2)
927 if r.get("_unitPrice") is not None:
928 r["unitPrice"], r["unitPriceUnit"] = r["_unitPrice"], r.get("_unitPriceUnit")
929 elif r.get("_unitPriceOk") is False:
930
931 r["unitPrice"], r["unitPriceUnit"] = None, None
932 elif r.get("unitPrice") is None:
933 r["unitPrice"], r["unitPriceUnit"] = unit_price(price, sz)
934 r["promotions"] = r.get("promotions") or []
935 if r.get("promoPrice") is None and price is not None:
936
937 offers = [p.get("promoUnitPrice") for p in r["promotions"] if isinstance(p, dict) and not p.get("memberOnly")
938 and p.get("minQuantity") == 1 and p.get("active", True) is not False
939 and isinstance(p.get("promoUnitPrice"), (int, float)) and 0 < p["promoUnitPrice"] < price]
940 r["promoPrice"] = min(offers) if offers else None
941 r["onSpecial"] = on_special(r)
942 if r.get("categories") and not r.get("category"):
943 r["category"] = " > ".join(str(c) for c in r["categories"] if c)
944 out = {k: r.get(k) for k in ROW_FIELDS}
945 for k, v in r.items():
946 if k not in out and not k.startswith("_"):
947 out[k] = v
948 return out
949
950
951class BaseAdapter:
952 """What every retailer adapter provides. The engine calls these; defaults suit a site without stores."""
953
954 retailer = ""
955 default_concurrency = 5
956 per_session = 3
957 min_interval = 0.15
958 source_parallelism = 3
959 context_sessions = False
960
961 async def contexts(self, eng: "Engine") -> list[Context]:
962 return [Context("", "default")]
963
964 async def build_sources(self, eng: "Engine") -> list[Source]:
965 raise NotImplementedError
966
967 async def setup(self, eng: "Engine") -> None:
968 return None
969
970 async def prepare_session(self, eng: "Engine", session: Session, ctx: Context | None) -> None:
971 return None
972
973 async def fetch_page(self, eng: "Engine", src: Source, cursor: Any) -> Page:
974 raise NotImplementedError
975
976 def wants_details(self, eng: "Engine", src: Source) -> bool:
977 return False
978
979 async def enrich(self, eng: "Engine", src: Source, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
980 return rows
981
982
983def standard_sources(eng: "Engine", classify: Any, contexts: list[Context] | None = None) -> list[Source]:
984 """Sources from `searchTerms` and `startUrls`, once per context (store or region).
985
986 `classify(url)` returns (kind, params, label) for a URL of this retailer, or a string saying why the URL cannot be
987 used. Unusable URLs are skipped with a warning; if nothing usable is left, the input is rejected."""
988 inp = eng.inp
989 terms = text_list(inp.get("searchTerms"))
990 urls = text_list(inp.get("startUrls"))
991
992
993 extra_terms: list[str] = []
994 for k in ("searches", "queries", "keywords", "search", "query", "searchTerm", "terms", "keyword", "q"):
995 extra_terms += text_list(inp.get(k))
996 extra_urls: list[str] = []
997 for k in ("urls", "links", "productUrls", "categoryUrls", "startUrl", "url", "productUrl", "categoryUrl"):
998 extra_urls += text_list(inp.get(k))
999 extra_urls += text_list([v for k, v in sorted(inp.items(), key=lambda kv: (len(kv[0]), kv[0])) if k.isdigit()])
1000 if extra_terms or extra_urls:
1001 eng.input_notes.append(f"{len(extra_terms) + len(extra_urls)} search term(s) or link(s) read from fields other than searchTerms/startUrls")
1002 looks_like_link = lambda s: bool(re.match(r"(?i)(https?://|www\.)", s)) or bool(re.match(r"(?i)[a-z0-9-]+(\.[a-z0-9-]+)*\.(co\.za|com|net|za)(/|$)", s))
1003 moved_t = [x for x in terms + extra_terms if looks_like_link(x)]
1004 moved_u = [x for x in urls + extra_urls if not looks_like_link(x) and "/" not in x]
1005 if moved_t:
1006 eng.input_notes.append(f"{len(moved_t)} link(s) in the search box read as links")
1007 if moved_u:
1008 eng.input_notes.append(f"{len(moved_u)} word(s) in the link box read as search terms")
1009 terms = list(dict.fromkeys([x for x in terms + extra_terms if not looks_like_link(x)] + moved_u))
1010 urls = list(dict.fromkeys([x for x in urls + extra_urls if looks_like_link(x) or "/" in x] + moved_t))
1011 ctxs = contexts or list(eng.contexts.values()) or [Context("", "default")]
1012 usable: list[tuple[str, dict[str, Any], str, str]] = []
1013 problems: list[str] = []
1014 for t in terms:
1015 if len(t) > 200:
1016 problems.append(f"search term too long: {t[:40]}...")
1017 continue
1018 usable.append(("search", {"value": t}, f'search "{t}"', "search:" + t.lower()))
1019 for u in urls:
1020 if "://" not in u:
1021 u = "https://" + u
1022 got = classify(u)
1023 if isinstance(got, str):
1024 problems.append(f"{u}: {got}")
1025 continue
1026 kind, params, label = got
1027 params.setdefault("value", u)
1028 usable.append((kind, params, label, f"{kind}:{params.get('id') or u}"))
1029 for n in eng.input_notes:
1030 Actor.log.info(f"Input: {n}")
1031 for p in problems[:30]:
1032 Actor.log.warning(f"Input skipped: {p}")
1033 eng.stats["inputsSkipped"] = len(problems)
1034 if not usable:
1035 if problems:
1036 raise InputError("None of the inputs can be used: " + "; ".join(problems[:5])[:480])
1037 return []
1038 sources: list[Source] = []
1039 for ctx in ctxs:
1040 for kind, params, label, key in usable:
1041 limit = 1 if kind == "product" else eng.per_source
1042 sources.append(Source(key=f"{key}@{ctx.key}", kind=kind,
1043 label=label + (f" ({ctx.label})" if ctx.key else ""),
1044 params=dict(params), context=ctx.key, limit=limit, base_label=label))
1045 return sources
1046
1047
1048async def pages_of(items: list[Any], size: int) -> AsyncIterator[list[Any]]:
1049 for i in range(0, len(items), size):
1050 yield items[i:i + size]