Buckets:

download
raw
24.2 kB
"""Database management commands for BLOOM CLI (TapDB-orchestrated)."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cli_core_yo.registry import CommandRegistry
from cli_core_yo.spec import CliSpec
import os
import subprocess
import sys
from pathlib import Path
import typer
import yaml
from daylily_tapdb.euid import (
AUDIT_LOG_PREFIX,
GENERIC_INSTANCE_LINEAGE_PREFIX,
GENERIC_TEMPLATE_PREFIX,
)
from daylily_tapdb.templates.loader import (
allow_template_mutations,
find_tapdb_core_config_dir,
seed_templates,
validate_template_configs,
)
from rich.console import Console
from sqlalchemy import text
from bloom_lims.cli._registry_v2 import (
EXEMPT_MUTATING,
EXEMPT_MUTATING_INTERACTIVE,
register_group_commands,
)
from bloom_lims.config import (
DEFAULT_BLOOM_TAPDB_LOCAL_PG_PORT,
DEFAULT_BLOOM_WEB_PORT,
DEFAULT_TAPDB_OWNER_REPO_NAME,
apply_runtime_environment,
get_settings,
)
from bloom_lims.tapdb_adapter import BLOOMdb3
from bloom_lims.template_identity import template_semantic_category
db_app = typer.Typer(help="Database management commands routed through daylily-tapdb.")
console = Console()
_TAPDB_CORE_TEMPLATE_PREFIXES = {"ADT", "EDG", "GSE", "GVR", "MSG", "SYS", "TPX", "XRF"}
_IDENTITY_PREFIXES: dict[str, str] = {
"generic_template": GENERIC_TEMPLATE_PREFIX,
"generic_instance_lineage": GENERIC_INSTANCE_LINEAGE_PREFIX,
"audit_log": AUDIT_LOG_PREFIX,
}
def _bloom_root() -> Path:
return Path(__file__).resolve().parents[2]
def _ensure_schema_available_for_bloom_root() -> None:
"""Require the repo-local TapDB schema file instead of discovering alternate copies."""
schema_path = (_bloom_root() / "schema" / "tapdb_schema.sql").resolve()
if schema_path.is_file():
return
raise RuntimeError(
"Bloom db bootstrap requires the repo-local schema file "
f"{schema_path}. Bloom will not guess schema sources from sibling repos, "
"site-packages, or Dayhoff artifacts."
)
def _tapdb_base_cmd() -> list[str]:
"""Run tapdb via module entrypoint to avoid PATH dependency issues."""
return [sys.executable, "-m", "daylily_tapdb.cli"]
def _runtime_env() -> dict[str, str]:
"""Build normalized runtime env for tapdb commands."""
settings = get_settings()
ctx = apply_runtime_environment(settings)
domain_registry_path = str(ctx.domain_registry_path).strip()
prefix_registry_path = str(ctx.prefix_ownership_registry_path).strip()
env = os.environ.copy()
env["AWS_PROFILE"] = ctx.aws_profile
env["AWS_REGION"] = ctx.aws_region
env["AWS_DEFAULT_REGION"] = ctx.aws_region
env["MERIDIAN_DOMAIN_CODE"] = ctx.domain_code
env["TAPDB_DOMAIN_CODE"] = ctx.domain_code
env["TAPDB_OWNER_REPO"] = ctx.owner_repo_name or DEFAULT_TAPDB_OWNER_REPO_NAME
env["TAPDB_SCHEMA_NAME"] = ctx.schema_name
env["TAPDB_DOMAIN_REGISTRY_PATH"] = domain_registry_path
env["TAPDB_PREFIX_OWNERSHIP_REGISTRY_PATH"] = prefix_registry_path
return env
def _ensure_runtime_config_parent() -> None:
config_path = (apply_runtime_environment(get_settings()).config_path or "").strip()
if not config_path:
return
Path(config_path).expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
def _current_target_label() -> str:
return apply_runtime_environment(get_settings()).target_label
def _confirm_target_label() -> str:
ctx = apply_runtime_environment(get_settings())
return (
f"{ctx.client_id}/{ctx.database_name}/"
f"{ctx.schema_name}@{ctx.physical_database or ctx.database_name}"
)
def _local_pg_port(target_label: str) -> str:
_ = target_label
settings = get_settings()
return str(
settings.tapdb.local_pg_port or DEFAULT_BLOOM_TAPDB_LOCAL_PG_PORT
).strip()
def _local_ui_port(target_label: str) -> str:
_ = target_label
return str(DEFAULT_BLOOM_WEB_PORT).strip()
def _tapdb_support_email(target_label: str) -> str:
_ = target_label
return get_settings().ui.support_email.strip()
def _update_tapdb_namespace_config(target_label: str) -> None:
_ = target_label
ctx = apply_runtime_environment(get_settings())
_run_tapdb(
[
"db-config",
"update",
"--support-email",
_tapdb_support_email("target"),
"--database",
ctx.physical_database or ctx.database_name,
"--schema-name",
ctx.schema_name,
]
)
def _run_tapdb(args: list[str], check: bool = True) -> int:
ctx = apply_runtime_environment(get_settings())
config_path = str(ctx.config_path or "").strip()
if not config_path:
raise RuntimeError(
"TapDB config path is required. Resolve it via Bloom settings and pass it explicitly "
"to TapDB with --config."
)
if config_path.startswith("~") or not Path(config_path).is_absolute():
raise RuntimeError(
f"TapDB config path must be a full absolute path. Got: {config_path}"
)
cmd = _tapdb_base_cmd() + [
"--config",
config_path,
]
cmd.extend(args)
env = _runtime_env()
result = subprocess.run(cmd, env=env)
if check and result.returncode != 0:
raise SystemExit(result.returncode)
return result.returncode
def _ensure_tapdb_namespace_config(
target_label: str, *, target_mode: str = "local"
) -> None:
"""Initialize or validate the explicit TapDB config for the requested target."""
_ = target_label
ctx = apply_runtime_environment(get_settings())
_ensure_runtime_config_parent()
config_path = Path(str(ctx.config_path)).expanduser().resolve()
if target_mode == "aurora":
if not config_path.is_file():
raise RuntimeError(
"Bloom Aurora db build requires an explicit pre-existing TapDB config at "
f"{config_path}. Dayhoff or `bloom config init` must materialize this file; "
"Bloom will not synthesize an Aurora target from local defaults."
)
root = yaml.safe_load(config_path.read_text(encoding="utf-8"))
if not isinstance(root, dict):
raise RuntimeError(
f"Bloom TapDB config must be a YAML mapping: {config_path}"
)
target = root.get("target")
if not isinstance(target, dict):
raise RuntimeError(
f"Bloom TapDB config is missing target mapping: {config_path}"
)
if str(target.get("engine_type") or "").strip().lower() != "aurora":
raise RuntimeError(
"Bloom Aurora db build requires target.engine_type=aurora in "
f"{config_path}"
)
for key in ("host", "port", "user", "database", "schema_name"):
if not str(target.get(key) or "").strip():
raise RuntimeError(
f"Bloom Aurora db build requires target.{key} in {config_path}"
)
if "password" not in target:
raise RuntimeError(
f"Bloom Aurora db build requires explicit target.password in {config_path}"
)
return
args = [
"db-config",
"init",
"--client-id",
ctx.client_id,
"--database-name",
ctx.database_name,
"--schema-name",
ctx.schema_name,
"--owner-repo-name",
ctx.owner_repo_name,
"--domain-code",
ctx.domain_code,
"--domain-registry-path",
str(ctx.domain_registry_path),
"--prefix-ownership-registry-path",
str(ctx.prefix_ownership_registry_path),
"--engine-type",
"local",
"--host",
"localhost",
"--port",
_local_pg_port("target"),
"--ui-port",
_local_ui_port("target"),
"--user",
"postgres",
"--database",
ctx.physical_database or ctx.database_name,
]
_run_tapdb(args)
_update_tapdb_namespace_config("target")
def _seed_tapdb_templates(
target_label: str,
*,
include_workflow: bool = False,
overwrite: bool = False,
) -> None:
"""Seed TapDB templates with strict per-owner prefix validation."""
tapdb_config_dir = (_bloom_root() / "config" / "tapdb_templates").resolve()
console.print(f"[cyan]TapDB template seed config:[/cyan] {tapdb_config_dir}")
if include_workflow:
raise RuntimeError("Workflow overlay seeding is not supported in Bloom.")
core_config_dir = find_tapdb_core_config_dir().resolve()
templates, issues = validate_template_configs(
[core_config_dir, tapdb_config_dir],
strict=True,
)
errors = [issue for issue in issues if issue.level == "error"]
if errors:
joined = "; ".join(issue.message for issue in errors)
raise RuntimeError(f"Bloom template pack validation failed: {joined}")
core_templates: list[dict[str, object]] = []
client_templates: list[dict[str, object]] = []
for template in templates:
instance_prefix = str(template.get("instance_prefix") or "").strip().upper()
target_batch = (
core_templates
if instance_prefix in _TAPDB_CORE_TEMPLATE_PREFIXES
else client_templates
)
target_batch.append(template)
ctx = apply_runtime_environment(get_settings())
domain_registry_path = Path(str(ctx.domain_registry_path)).expanduser().resolve()
prefix_registry_path = (
Path(str(ctx.prefix_ownership_registry_path)).expanduser().resolve()
)
bdb = BLOOMdb3(app_username="bloom-cli")
try:
if core_templates:
_ensure_identity_prefix_config(
bdb.session,
owner_repo_name="daylily-tapdb",
domain_code=ctx.domain_code,
)
seed_templates(
bdb.session,
core_templates,
overwrite=True,
core_config_dir=core_config_dir,
domain_code=ctx.domain_code,
owner_repo_name="daylily-tapdb",
domain_registry_path=domain_registry_path,
prefix_registry_path=prefix_registry_path,
)
if client_templates:
client_templates = [
template
for template in client_templates
if str(template.get("instance_prefix") or "").strip().upper()
not in _TAPDB_CORE_TEMPLATE_PREFIXES
]
_claim_client_template_prefixes(
prefix_registry_path=prefix_registry_path,
domain_code=ctx.domain_code,
owner_repo_name=ctx.owner_repo_name,
templates=client_templates,
)
_ensure_identity_prefix_config(
bdb.session,
owner_repo_name=ctx.owner_repo_name,
domain_code=ctx.domain_code,
)
seed_templates(
bdb.session,
client_templates,
overwrite=overwrite,
core_config_dir=core_config_dir,
domain_code=ctx.domain_code,
owner_repo_name=ctx.owner_repo_name,
domain_registry_path=domain_registry_path,
prefix_registry_path=prefix_registry_path,
)
if overwrite:
retired = _retire_obsolete_template_variants(
bdb.session,
bdb.Base.classes.generic_template,
client_templates,
domain_code=ctx.domain_code,
)
if retired:
console.print(
"[cyan]Retired obsolete Bloom template variants:[/cyan] "
f"{retired}"
)
bdb.session.commit()
except Exception:
bdb.session.rollback()
raise
finally:
bdb.session.close()
bdb.engine.dispose()
def _active_template_categories_by_semantic_key(
templates: list[dict[str, object]],
) -> dict[tuple[str, str, str, str], str]:
current: dict[tuple[str, str, str, str], str] = {}
for template in templates:
payload = template.get("json_addl")
if not isinstance(payload, dict):
payload = {}
semantic_category = str(payload.get("semantic_category") or "").strip().lower()
type_name = str(template.get("type") or "").strip()
if not semantic_category or not type_name:
continue
subtype = str(template.get("subtype") or "").strip()
version = str(template.get("version") or "").strip()
category = str(template.get("category") or "").strip().upper()
if subtype and version and category:
current[(semantic_category, type_name, subtype, version)] = category
return current
def _retire_obsolete_template_variants(
session,
template_model,
templates: list[dict[str, object]],
*,
domain_code: str,
) -> int:
current = _active_template_categories_by_semantic_key(templates)
current_semantic_types = {
(
str((template.get("json_addl") or {}).get("semantic_category") or "")
.strip()
.lower(),
str(template.get("type") or "").strip(),
)
for template in templates
if isinstance(template.get("json_addl"), dict)
and str(
(template.get("json_addl") or {}).get("semantic_category") or ""
).strip()
and str(template.get("type") or "").strip()
}
current_prefixes = {
str(template.get("instance_prefix") or "").strip().upper()
for template in templates
if str(template.get("instance_prefix") or "").strip()
}
if not current and not current_prefixes:
return 0
rows = (
session.query(template_model)
.filter(
template_model.domain_code == str(domain_code or "").strip().upper(),
template_model.is_deleted == False, # noqa: E712
)
.all()
)
retired = 0
with allow_template_mutations():
for row in rows:
key = (
template_semantic_category(row).strip().lower(),
str(row.type or "").strip(),
str(row.subtype or "").strip(),
str(row.version or "").strip(),
)
expected_category = current.get(key)
actual_category = str(row.category or "").strip().upper()
if actual_category in current_prefixes:
row.is_deleted = True
row.bstatus = "retired"
retired += 1
continue
if expected_category is None:
if (key[0], key[1]) in current_semantic_types:
row.is_deleted = True
row.bstatus = "retired"
retired += 1
continue
if actual_category == expected_category:
continue
row.is_deleted = True
row.bstatus = "retired"
retired += 1
if retired:
session.flush()
return retired
def _load_prefix_ownership_registry(path: Path) -> dict[str, object]:
if not path.exists():
return {"version": "0.4.0", "ownership": {}}
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError(f"Prefix ownership registry must be a JSON object: {path}")
ownership = payload.get("ownership")
if ownership is None:
payload["ownership"] = {}
elif not isinstance(ownership, dict):
raise ValueError(
f"Prefix ownership registry must define object ownership: {path}"
)
if "version" not in payload:
payload["version"] = "0.4.0"
return payload
def _write_prefix_ownership_registry(path: Path, payload: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(payload, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
try:
path.chmod(0o600)
except Exception:
pass
def _claim_client_template_prefixes(
*,
prefix_registry_path: Path,
domain_code: str,
owner_repo_name: str,
templates: list[dict[str, object]],
) -> None:
normalized_domain_code = str(domain_code or "").strip().upper()
normalized_owner_repo_name = str(owner_repo_name or "").strip()
if not normalized_domain_code:
raise ValueError("domain_code is required to claim client template prefixes")
if not normalized_owner_repo_name:
raise ValueError(
"owner_repo_name is required to claim client template prefixes"
)
prefixes = sorted(
{
str(template.get("instance_prefix") or "").strip().upper()
for template in templates
if str(template.get("instance_prefix") or "").strip()
and str(template.get("instance_prefix") or "").strip().upper()
not in _TAPDB_CORE_TEMPLATE_PREFIXES
}
)
if not prefixes:
return
registry = _load_prefix_ownership_registry(prefix_registry_path)
ownership = registry.get("ownership")
if ownership is None:
ownership = {}
registry["ownership"] = ownership
if not isinstance(ownership, dict):
raise ValueError(
f"Prefix ownership registry must define object ownership: {prefix_registry_path}"
)
domain_claims = ownership.get(normalized_domain_code)
if domain_claims is None:
domain_claims = {}
ownership[normalized_domain_code] = domain_claims
if not isinstance(domain_claims, dict):
raise ValueError(
f"Prefix ownership registry must define object ownership for domain "
f"{normalized_domain_code!r}: {prefix_registry_path}"
)
changed = False
for prefix in prefixes:
existing = domain_claims.get(prefix)
if isinstance(existing, dict):
claimed_owner = str(
existing.get("issuer_app_code")
or existing.get("owner_repo_name")
or existing.get("repo_name")
or ""
).strip()
if claimed_owner and claimed_owner != normalized_owner_repo_name:
raise ValueError(
f"Prefix {prefix!r} for domain {normalized_domain_code!r} is claimed by "
f"{claimed_owner!r}, not {normalized_owner_repo_name!r}"
)
if (
claimed_owner != normalized_owner_repo_name
or existing.get("issuer_app_code") != normalized_owner_repo_name
):
domain_claims[prefix] = {"issuer_app_code": normalized_owner_repo_name}
changed = True
continue
if existing is not None:
raise ValueError(
f"Prefix {prefix!r} for domain {normalized_domain_code!r} has an invalid "
f"claim entry in {prefix_registry_path}"
)
domain_claims[prefix] = {"issuer_app_code": normalized_owner_repo_name}
changed = True
if changed:
_write_prefix_ownership_registry(prefix_registry_path, registry)
def _ensure_identity_prefix_config(
session, *, owner_repo_name: str, domain_code: str
) -> None:
values_sql = ",\n ".join(
f"('{entity}', '{domain_code}', '{owner_repo_name}', '{prefix}')"
for entity, prefix in _IDENTITY_PREFIXES.items()
)
sequence_sql = "\n ".join(
f'CREATE SEQUENCE IF NOT EXISTS "{prefix.lower()}_instance_seq";'
for prefix in sorted(set(_IDENTITY_PREFIXES.values()))
)
sql = f"""
INSERT INTO tapdb_identity_prefix_config(entity, domain_code, issuer_app_code, prefix)
VALUES {values_sql}
ON CONFLICT (entity, domain_code, issuer_app_code) DO UPDATE
SET prefix = EXCLUDED.prefix, updated_dt = NOW();
{sequence_sql}
"""
session.execute(text(sql))
@db_app.command("build")
def db_build(
force: bool = typer.Option(False, "--force", "-f", help="Force re-initialization"),
target: str = typer.Option(
"local",
"--target",
help="TapDB build target: local or aurora",
),
) -> None:
"""Build database/runtime via tapdb orchestration."""
target_mode = target.strip().lower()
if target_mode not in {"local", "aurora"}:
raise typer.BadParameter("--target must be either local or aurora")
console.print(
f"[cyan]Initializing BLOOM database via tapdb (target={target_mode})...[/cyan]"
)
target_label = _current_target_label()
_ensure_tapdb_namespace_config(target_label, target_mode=target_mode)
if target_mode == "local":
_ensure_schema_available_for_bloom_root()
local_port = _local_pg_port(target_label)
console.print(f"[cyan]Using local TapDB PostgreSQL port {local_port}[/cyan]")
_run_tapdb(["pg", "init"], check=False)
_run_tapdb(["pg", "start-local", "--port", local_port])
_run_tapdb(["db", "create"], check=False)
schema_args = ["db", "schema", "apply"]
if force:
schema_args.append("--reinitialize")
_run_tapdb(schema_args)
_run_tapdb(["db", "schema", "migrate"])
_seed_tapdb_templates(target_label, overwrite=force)
return
_ensure_schema_available_for_bloom_root()
_run_tapdb(["db", "create"], check=False)
schema_args = ["db", "schema", "apply"]
if force:
schema_args.append("--reinitialize")
_run_tapdb(schema_args)
_run_tapdb(["db", "schema", "migrate"])
_seed_tapdb_templates(target_label, overwrite=force)
@db_app.command("seed")
def db_seed() -> None:
"""Seed template data via tapdb."""
target_label = _current_target_label()
_seed_tapdb_templates(target_label, include_workflow=False, overwrite=False)
@db_app.command("refresh-templates")
def db_refresh_templates() -> None:
"""Refresh active Bloom templates without resetting schema or objects."""
target_label = _current_target_label()
_ensure_schema_available_for_bloom_root()
_seed_tapdb_templates(target_label, include_workflow=False, overwrite=True)
@db_app.command("reset")
def db_reset(
yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
) -> None:
"""Reset schema/data and rebuild via tapdb (destructive)."""
target_label = _current_target_label()
if not yes:
console.print(
"[yellow]WARNING: This will drop all data and rebuild the schema.[/yellow]"
)
if not typer.confirm("Are you sure you want to continue?"):
console.print("[dim]Aborted.[/dim]")
return
_ensure_schema_available_for_bloom_root()
_run_tapdb(["db", "schema", "reset", "--confirm-target", _confirm_target_label()])
_run_tapdb(["db", "setup"])
_seed_tapdb_templates(target_label, include_workflow=False, overwrite=True)
@db_app.command("nuke")
def db_nuke(
force: bool = typer.Option(
False, "--force", "-f", help="Force destructive schema reset"
),
) -> None:
"""Delete schema only via TapDB."""
_ = _current_target_label()
args = ["db", "schema", "reset"]
if force:
args.extend(["--confirm-target", _confirm_target_label()])
_run_tapdb(args)
def register(registry: CommandRegistry, spec: CliSpec) -> None:
"""cli-core-yo plugin: register the db command group."""
_ = spec
register_group_commands(
registry,
"db",
"Database management commands.",
[
("build", db_build, EXEMPT_MUTATING),
("seed", db_seed, EXEMPT_MUTATING),
("refresh-templates", db_refresh_templates, EXEMPT_MUTATING),
("reset", db_reset, EXEMPT_MUTATING_INTERACTIVE),
("nuke", db_nuke, EXEMPT_MUTATING_INTERACTIVE),
],
)

Xet Storage Details

Size:
24.2 kB
·
Xet hash:
e62f79e9b0ceb14b34561ef3cbcdfa73b0fa48c2bcb9defe419b0ad39f07c8f7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.