"""Build the ``ChxPlugin`` object that registers the ObsessionDB hooks + commands. The factory ``obsessiondb()`` is what the user puts in their ``clickhouse.config.py`` ``plugins`` list. It contributes: - ``on_schema_loaded`` — auto-rewrites ``Shared*`` engines + strips cloud-only settings when the target isn't an ObsessionDB host. - Auth commands: ``login``, ``signup``, ``logout``, ``whoami`` — dispatched via ``chkit plugin obsessiondb ``. - ``get_context`` — hands out the remote executor when logged in with a service selected (or named with ``--service``), so commands need no ``clickhouse`` block. - Service commands (list / select / claim / alias) and ``on_before_plugin_command`` for backfill routing. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Any from chkit.cli.plugin_runtime import make_plugin_context from chkit.cli.shared_engine_flags import ( FORCE_SHARED_ENGINES_HELP, NO_SHARED_ENGINES_HELP, ) from chkit.core import load_schema_definitions from chkit.plugins import ( ChxCheckFinding, ChxGetContextInput, ChxOnBeforePluginCommandContext, ChxOnBeforePluginCommandResult, ChxOnCheckContext, ChxOnCheckReportContext, ChxOnCheckResult, ChxOnInitContext, ChxOnPlanCreatedContext, ChxOnSchemaLoadedContext, ChxPlugin, ChxPluginCommand, ChxPluginCommandContext, ChxPluginManifest, PluginContext, ) from chkit_plugin_obsessiondb.auth_login import ( run_login, run_logout, run_whoami, ) from chkit_plugin_obsessiondb.auth_signup import ( SignupOptions, run_signup, ) from chkit_plugin_obsessiondb.backfill_check import check_submitted_backfill_jobs from chkit_plugin_obsessiondb.backfill_handler import handle_backfill_command from chkit_plugin_obsessiondb.backfill_plugin_options import resolve_backfill_state_dir from chkit_plugin_obsessiondb.credentials import ( Credentials, load_credentials, resolve_base_url, ) from chkit_plugin_obsessiondb.engine import ( find_distributed_tables, is_obsessiondb_target, resolve_strip_behavior, rewrite_shared_engines, storage_policy_change_errors, with_obsessiondb_storage_policy, ) from chkit_plugin_obsessiondb.remote_executor import create_remote_executor from chkit_plugin_obsessiondb.service_api import list_services from chkit_plugin_obsessiondb.service_commands import service_command_run from chkit_plugin_obsessiondb.storage import ( SelectedService, load_selected_service, load_service_aliases, ) @dataclass(frozen=True, slots=True) class ObsessionDBPluginOptions: """Plugin factory options. Reserved for future tunables.""" @dataclass class _ObsessionDBHooks: """Concrete hook object the plugin runtime introspects via ``hasattr``.""" json_mode_default: bool = False def get_context(self, ctx: ChxGetContextInput) -> PluginContext | None: # TS getContext: logged in with a service selected (or named with # --service) routes SQL through the ObsessionDB API instead of the # `clickhouse` block. session = _load_session(ctx.config_path, ctx.flags) if session is None: return None creds, service = session executor = create_remote_executor(creds, service_slug=service.service_slug) return make_plugin_context(executor) def on_init(self, ctx: ChxOnInitContext) -> None: # TS onInit: say which service SQL goes to, since it takes precedence # over a `clickhouse` block. An unknown --service fails in get_context. if ctx.json_mode or ctx.command == "obsessiondb": return try: session = _load_session(ctx.config_path, ctx.flags) except Exception: return if session is not None: _creds, service = session print(f'obsessiondb: using service "{service.service_name}"\n') def on_before_plugin_command( self, ctx: ChxOnBeforePluginCommandContext ) -> ChxOnBeforePluginCommandResult: return handle_backfill_command(ctx) def on_schema_loaded( self, ctx: ChxOnSchemaLoadedContext ) -> list[Any] | None: flags = dict(ctx.flags) if ctx.flags else {} if not resolve_strip_behavior(ctx.config, flags): distributed = find_distributed_tables(list(ctx.definitions)) if distributed: raise ValueError("\n".join(distributed)) if is_obsessiondb_target(ctx.config, flags): return with_obsessiondb_storage_policy(list(ctx.definitions)) return None result = rewrite_shared_engines(list(ctx.definitions)) if not ctx.json_mode: if result.count > 0: print( f"obsessiondb: Rewrote {result.count} Shared engine(s) " f"to standard ClickHouse equivalents." ) if result.stripped_settings: unique = sorted(set(result.stripped_settings)) print( f"obsessiondb: Stripped cloud-only setting(s): " f"{', '.join(unique)}" ) return result.definitions def on_snapshot_loaded(self, ctx: ChxOnSchemaLoadedContext) -> list[Any]: # The same settings rewrite as on_schema_loaded, without its notices # and checks: they are about the schema, not about the last snapshot. flags = dict(ctx.flags) if ctx.flags else {} if resolve_strip_behavior(ctx.config, flags): return rewrite_shared_engines(list(ctx.definitions)).definitions if is_obsessiondb_target(ctx.config, flags): return with_obsessiondb_storage_policy(list(ctx.definitions)) return list(ctx.definitions) def on_plan_created(self, ctx: ChxOnPlanCreatedContext) -> Any: flags = dict(ctx.flags) if ctx.flags else {} if not is_obsessiondb_target(ctx.config, flags): return None errors = storage_policy_change_errors(ctx.plan) if errors: raise ValueError("\n".join(errors)) return None def on_check(self, ctx: ChxOnCheckContext) -> ChxOnCheckResult | None: # Same target decision as on_schema_loaded: ObsessionDB host or # --force-shared-engines. flags = dict(ctx.flags) if ctx.flags else {} distributed_findings: list[ChxCheckFinding] | None = None if not resolve_strip_behavior(ctx.config, flags): definitions = load_schema_definitions( list(ctx.config.schema_), cwd=Path(ctx.config_path).resolve().parent ) distributed_findings = [ ChxCheckFinding( code="obsessiondb_distributed_unsupported", message=message, severity="error", ) for message in find_distributed_tables(definitions) ] # Submitted backfill jobs run on ObsessionDB whatever the check target is. backfill_jobs = check_submitted_backfill_jobs( config=ctx.config, config_path=ctx.config_path, state_dir=resolve_backfill_state_dir(ctx.config.plugins), ) if distributed_findings is None and backfill_jobs is None: return None findings = [ *(distributed_findings or []), *(backfill_jobs.findings if backfill_jobs else []), ] return ChxOnCheckResult( plugin="obsessiondb", evaluated=True, ok=not findings, findings=findings, metadata=( {"backfillJobs": backfill_jobs.counts.to_metadata()} if backfill_jobs else None ), ) def on_check_report(self, ctx: ChxOnCheckReportContext) -> None: if ctx.result.ok: return for finding in ctx.result.findings: ctx.print(f"obsessiondb: {finding.message}") def _load_session( config_path: str, flags: dict[str, Any] ) -> tuple[Credentials, SelectedService] | None: """The stored login and the service named by --service, else the project's selected service, or None without both.""" stored = load_credentials() if stored is None: return None creds = Credentials( access_token=stored.access_token, base_url=resolve_base_url(stored.base_url) ) override = flags.get("--service") override_name = override.strip() if isinstance(override, str) else "" service = ( _resolve_service_override(creds, config_path, override_name) if override_name else load_selected_service(config_path) ) if service is None: return None return creds, service def _resolve_service_override( creds: Credentials, config_path: str, name: str ) -> SelectedService: """Port of TS ``resolveServiceOverride``: a service name, then an alias.""" services = list_services(creds) for candidate in services: if candidate.name == name: return SelectedService(service_slug=candidate.slug, service_name=candidate.name) aliases = load_service_aliases(config_path).aliases alias = aliases.get(name) if alias is not None: return alias available_services = ", ".join(c.name for c in services) or "" available_aliases = ", ".join(sorted(aliases)) or "" msg = ( f'obsessiondb: service "{name}" not found. Available services: ' f"{available_services}. Available aliases: {available_aliases}" ) raise ValueError(msg) _API_URL_FLAG: dict[str, Any] = { "name": "--api-url", "type": "string", "description": "ObsessionDB API base URL", } # The TS `signup` flags, in its order and words. _SIGNUP_FLAGS: list[dict[str, Any]] = [ { "name": "--email", "type": "string", "description": "Email to sign up/log in with (skips the prompt)", }, { "name": "--code", "type": "string", "description": "One-time code (skips the prompt; for scripts/tests)", }, { "name": "--org-name", "type": "string", "description": "Override the auto-created organization name", }, { "name": "--request-only", "type": "boolean", "description": "Only send the code and print the follow-up command (step 1 of 2)", }, ] def _resolve_base_url_from_flags(flags: dict[str, Any]) -> str: """``--api-url`` overrides anything else; otherwise fall back to env/stored/default.""" candidate = flags.get("--api-url") or flags.get("api_url") if isinstance(candidate, str) and candidate.strip(): return candidate.strip() return resolve_base_url() def _login_run(ctx: ChxPluginCommandContext) -> int: base_url = _resolve_base_url_from_flags(ctx.flags) return run_login(base_url, Path(ctx.config_path), ctx.print) def _logout_run(ctx: ChxPluginCommandContext) -> int: return run_logout(ctx.print) def _whoami_run(ctx: ChxPluginCommandContext) -> int: return run_whoami(ctx.print, json_mode=ctx.json_mode) def _signup_run(ctx: ChxPluginCommandContext) -> int: base_url = _resolve_base_url_from_flags(ctx.flags) options = SignupOptions( email=_str_flag(ctx.flags, "--email"), code=_str_flag(ctx.flags, "--code"), org_name=_str_flag(ctx.flags, "--org-name"), request_only=bool(ctx.flags.get("--request-only") or ctx.flags.get("request_only")), json_mode=ctx.json_mode, ) return run_signup(base_url, ctx.print, options) def _str_flag(flags: dict[str, Any], name: str) -> str | None: value = flags.get(name) or flags.get(name.lstrip("-").replace("-", "_")) if isinstance(value, str) and value.strip(): return value.strip() return None def create_obsessiondb_plugin( _options: ObsessionDBPluginOptions | None = None, ) -> ChxPlugin: """Return a ``ChxPlugin`` for inclusion in ``config.plugins``.""" return ChxPlugin( manifest=ChxPluginManifest(name="obsessiondb", api_version=1), hooks=_ObsessionDBHooks(), # In the TS order and wording, which `chkit obsessiondb -h` and # `chkit plugin obsessiondb` print and an unknown command's error names. commands=[ ChxPluginCommand( name="login", description="Authenticate with ObsessionDB", run=_login_run, flags=[_API_URL_FLAG], takes_args=False, ), ChxPluginCommand( name="signup", description="Sign up or log in with a one-time email code (passwordless)", run=_signup_run, flags=[_API_URL_FLAG, *_SIGNUP_FLAGS], takes_args=False, ), ChxPluginCommand( name="logout", description="Remove stored ObsessionDB credentials", run=_logout_run, takes_args=False, ), ChxPluginCommand( name="whoami", description="Show current ObsessionDB user", run=_whoami_run, takes_args=False, ), ChxPluginCommand( name="service", description="Manage ObsessionDB services", run=service_command_run, ), ], # Mirror of TS BACKFILL_EXTEND_COMMANDS: register the remote-routing # flags against the `backfill` plugin commands so the dispatcher # accepts them and the on_before_plugin_command hook can route on them. extend_commands=[ # Mirror of the TS shared-engine override flags. Only `generate` and # `snapshot rebuild` run the on_schema_loaded hooks, so only they act # on these flags (chkit-py declares them as Typer options on those two # commands; see chkit.cli.shared_engine_flags). { "command": ["generate", "migrate", "status", "drift", "check", "snapshot"], "flags": [ { "name": "--force-shared-engines", "type": "boolean", "description": FORCE_SHARED_ENGINES_HELP, }, { "name": "--no-shared-engines", "type": "boolean", "description": NO_SHARED_ENGINES_HELP, }, ], }, { "command": ["backfill"], "flags": [ { "name": "--local", "type": "boolean", "description": "Force local execution (skip remote routing)", }, ], }, { "command": ["backfill"], "flags": [ { "name": "--job-id", "type": "string", "description": "Remote job ID for status/cancel", }, { "name": "--service-slug", "type": "string", "description": ( "ObsessionDB service slug for listing jobs" " (list defaults to the selected service)" ), }, ], }, ], ) def obsessiondb( options: ObsessionDBPluginOptions | None = None, ) -> ChxPlugin: """Public factory matching the TS ``obsessiondb()`` registration helper.""" return create_obsessiondb_plugin(options)