ReMe/reme/components/client/base_client.py
jinliyl 54fa3381d7
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
refactor(core): reorganize the ReMe runtime and shared helpers (#769)
* refactor(core): reorganize the ReMe runtime and shared helpers

* test(status): import the base component from its canonical module

* test: remove redundant unit checks

* refactor(core): use canonical runtime imports and shared CLI discovery

Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service.

* fix(cli): honor caller config when service replay is incomplete

Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
2026-11-20 22:06:46 +08:00

74 lines
2.8 KiB
Python

"""Base client abstraction."""
import json
import os
from abc import abstractmethod
from collections.abc import AsyncGenerator
import httpx
from ..base import BaseComponent
from ...constants import (
REME_DEFAULT_HOST,
REME_DEFAULT_PORT,
REME_SERVICE_INFO,
normalize_connect_host,
)
from ...enumeration import ComponentEnum
class BaseClient(BaseComponent):
"""Abstract base for clients that communicate with ReMe services."""
component_type = ComponentEnum.CLIENT
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.client = None
def _resolve_service_address(self, host: str | None, port: int | None) -> tuple[str, int]:
"""Resolve explicit, discovered, or default network coordinates."""
if not (host and port):
fallback_host, fallback_port = REME_DEFAULT_HOST, REME_DEFAULT_PORT
if service_info := os.environ.get(REME_SERVICE_INFO):
try:
data = json.loads(service_info)
fallback_host, fallback_port = data["host"], data["port"]
except Exception:
self.logger.warning(f"Invalid service info: {service_info}")
host = host or fallback_host
port = port or fallback_port
return normalize_connect_host(host), port
@staticmethod
def _build_service_url(host: str, port: int, path: str = "") -> str:
"""Build a valid HTTP URL for the resolved service address, including IPv6 literals."""
return str(httpx.URL(scheme="http", host=host, port=port, path=path))
async def _start(self) -> None:
"""Initialize the client."""
async def _close(self) -> None:
"""Close the client and release resources."""
@abstractmethod
def _execute(self, action: str, payload: dict) -> AsyncGenerator[str, None]:
"""Backend-specific execution; yield text chunks (single yield for non-streaming backends)."""
@abstractmethod
async def list_actions(self) -> list[dict]:
"""Discover available actions on the server; each dict is the raw backend descriptor."""
async def __call__(self, action: str, **kwargs) -> AsyncGenerator[str, None]:
"""Dispatch: action='list' returns the action catalog; otherwise delegate to _execute()."""
async for chunk in self.call_job(action, kwargs):
yield chunk
async def call_job(self, job_name: str, payload: dict) -> AsyncGenerator[str, None]:
"""Pass job arguments as a mapping so names such as ``action`` remain usable."""
if job_name == "list":
actions = await self.list_actions()
yield json.dumps(actions, indent=2, ensure_ascii=False)
return
async for chunk in self._execute(job_name, payload):
yield chunk