Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : sdk/python/spider_sdk/_sync.py8# Module : Sdk9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Synchronous client: the surface of :class:`AsyncSpider`, method for method."""42from __future__ import annotations4344import asyncio45import functools46import inspect47import threading48from collections.abc import Iterator49from typing import Any, Self5051from ._client import AsyncSpider525354class Spider:55 """Blocking SPIDER client.5657 Every public method of :class:`AsyncSpider` exists here with the same name, parameters and58 semantics; asynchronous iterators (``iter_results``, ``iter_jobs``, ``iter_search``,59 ``stream_events``) become ordinary iterators. The work runs on a private event loop in a daemon60 thread, so the client is usable from plain scripts and from threads. Close it with ``close()``61 or use it as a context manager.62 """6364 def __init__(self, base_url: str, api_key: str, **options: Any) -> None:65 self._loop = asyncio.new_event_loop()66 self._thread = threading.Thread(target=self._loop.run_forever, name="spider-sdk", daemon=True)67 self._thread.start()68 try:69 self._async = self._run(self._make(base_url, api_key, options))70 except BaseException:71 self._stop()72 raise7374 @staticmethod75 async def _make(base_url: str, api_key: str, options: dict[str, Any]) -> AsyncSpider:76 return AsyncSpider(base_url, api_key, **options)7778 def _run(self, coro: Any) -> Any:79 return asyncio.run_coroutine_threadsafe(coro, self._loop).result()8081 def _stop(self) -> None:82 if not self._loop.is_closed():83 self._loop.call_soon_threadsafe(self._loop.stop)84 self._thread.join(timeout=5)85 self._loop.close()8687 def _iterate(self, agen: Any) -> Iterator[Any]:88 try:89 while True:90 try:91 yield self._run(agen.__anext__())92 except StopAsyncIteration:93 return94 finally:95 self._run(agen.aclose())9697 @property98 def base_url(self) -> str:99 return self._async.base_url100101 def __repr__(self) -> str:102 return f"Spider(base_url={self.base_url!r}, api_key='***')"103104 def __enter__(self) -> Self:105 return self106107 def __exit__(self, *exc: object) -> None:108 self.close()109110 def close(self) -> None:111 if not self._loop.is_closed():112 self._run(self._async.aclose())113 self._stop()114115116def _sync_method(name: str, fn: Any) -> Any:117 if inspect.isasyncgenfunction(fn):118 @functools.wraps(fn)119 def gen(self: Spider, *args: Any, **kwargs: Any) -> Iterator[Any]:120 return self._iterate(getattr(self._async, name)(*args, **kwargs))121 return gen122123 @functools.wraps(fn)124 def call(self: Spider, *args: Any, **kwargs: Any) -> Any:125 return self._run(getattr(self._async, name)(*args, **kwargs))126 return call127128129SYNC_METHODS: list[str] = []130for _name, _fn in vars(AsyncSpider).items():131 if _name.startswith("_") or _name == "aclose" or isinstance(_fn, staticmethod):132 continue133 if inspect.iscoroutinefunction(_fn) or inspect.isasyncgenfunction(_fn):134 setattr(Spider, _name, _sync_method(_name, _fn))135 SYNC_METHODS.append(_name)136