ReMe/reme/components/service/base_service.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

109 lines
4.2 KiB
Python

"""Base class for services that expose jobs over a network protocol."""
import json
import os
from abc import abstractmethod
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING
from ..base import BaseComponent
from ..job.base_job import BaseJob
from ...constants import REME_SERVICE_INFO, normalize_connect_host
from ...enumeration import ComponentEnum
if TYPE_CHECKING:
from ...core.application import Application
class BaseService(BaseComponent):
"""Skeleton for services (HTTP, MCP, ...) that turn jobs into endpoints or tools."""
component_type = ComponentEnum.SERVICE
def __init__(self, jobs: list[str] | None = None, **kwargs):
super().__init__(**kwargs)
self.jobs: set[str] | None = set(jobs) if jobs is not None else None
# Underlying framework instance (FastAPI, FastMCP, ...); populated by build_service().
self.service = None
# ----- Subclass contract ---------------------------------------------
@abstractmethod
def build_service(self, app: "Application") -> None:
"""Instantiate and configure the underlying server framework."""
@abstractmethod
def add_job(self, job: BaseJob) -> bool:
"""Register a single job as a callable endpoint or tool.
Returns True when the job is exposed, False when the service intentionally
skips it (for example, unsupported job types).
"""
@abstractmethod
def start_service(self, app: "Application") -> None:
"""Block on serving requests until shutdown."""
def finalize_service(self, app: "Application") -> None:
"""Register routes that must be added after every configured job."""
# ----- Shared helpers ------------------------------------------------
def _lifespan(self, app: "Application", host: str, port: int):
"""Build an async-context lifespan that brackets the server with app start/close.
Publishes a connectable address via the REME_SERVICE_INFO environment variable
so in-process clients can discover the service even when it binds a wildcard.
"""
@asynccontextmanager
async def lifespan(_):
await app.start()
try:
advertised_host = normalize_connect_host(host)
service_info = json.dumps({"host": advertised_host, "port": port})
os.environ[REME_SERVICE_INFO] = service_info
self.logger.info(f"{self.name} started: {REME_SERVICE_INFO}={service_info}")
yield
finally:
await app.close()
return lifespan
def add_jobs(self, app: "Application") -> None:
"""Register service-enabled jobs, optionally restricted by the configured whitelist."""
if self.jobs is not None:
missing = sorted(self.jobs.difference(app.context.jobs))
if missing:
raise KeyError(f"Service jobs not found: {', '.join(missing)}")
disabled = sorted(
name
for name in self.jobs
if not app.context.jobs[name].enabled or not app.context.jobs[name].enable_serve
)
if disabled:
raise ValueError(f"Service jobs are not enabled for serving: {', '.join(disabled)}")
for name, job in app.context.jobs.items():
if not job.enabled or not job.enable_serve or (self.jobs is not None and name not in self.jobs):
continue
try:
added = self.add_job(job)
except Exception as e:
if self.jobs is not None:
raise
self.logger.error(f"Failed to add job {name}: {e}")
continue
if added:
self.logger.info(f"Added job: {name}")
elif self.jobs is not None:
raise TypeError(f"Service does not support job: {name}")
else:
self.logger.warning(f"Skipped job: {name}")
def run_app(self, app: "Application") -> None:
"""Build the service, register jobs, then start serving (blocking)."""
self.build_service(app)
self.add_jobs(app)
self.finalize_service(app)
self.start_service(app)