forked from linkong/planet
181 lines
6.8 KiB
Python
181 lines
6.8 KiB
Python
"""Bounded catalog queries and type defaults for every Earth object card."""
|
|
|
|
from sqlalchemy import String, case, cast, func, literal, or_, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.compute_types import (
|
|
COMPUTE_SITE_TYPES,
|
|
compute_site_type_expression,
|
|
compute_record_filter,
|
|
)
|
|
from app.models.bgp_incident import BGPIncident
|
|
from app.models.bgp_collector_location import BGPCollectorLocation
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.earth_interactable import EarthInteractable
|
|
from app.models.vessel import VesselCurrentState
|
|
from app.schemas.card_images import EntityType, MatchScope
|
|
|
|
SOURCES = {
|
|
"satellite": ("celestrak_tle", "spacetrack_tle"),
|
|
"compute_center": ("top500", "epoch_ai_gpu"),
|
|
"cable": ("arcgis_cables",),
|
|
"landing_point": ("arcgis_landing_points",),
|
|
}
|
|
# Named constellation families, not inferred hardware models or generations.
|
|
SATELLITE_GROUP_PATTERNS = (
|
|
("STARLINK%", "starlink"),
|
|
("IRIDIUM%", "iridium-next"),
|
|
("BEIDOU-3%", "beidou-3"),
|
|
("BEIDOU%", "beidou"),
|
|
("QIANFAN%", "qianfan"),
|
|
("ONEWEB%", "oneweb"),
|
|
("KUIPER%", "kuiper"),
|
|
)
|
|
|
|
|
|
def collected_query(entity_type: EntityType):
|
|
record, metadata = CollectedData, CollectedData.extra_data
|
|
model = func.coalesce(
|
|
metadata["satellite_model" if entity_type == "satellite" else "model"].as_string(), ""
|
|
)
|
|
category = (
|
|
compute_site_type_expression(record)
|
|
if entity_type == "compute_center"
|
|
else literal(entity_type)
|
|
)
|
|
if entity_type == "satellite":
|
|
group = func.coalesce(
|
|
func.nullif(func.lower(metadata["constellation_group"].as_string()), ""),
|
|
case(
|
|
*[
|
|
(func.upper(record.name).like(pattern), value)
|
|
for pattern, value in SATELLITE_GROUP_PATTERNS
|
|
],
|
|
else_="",
|
|
),
|
|
)
|
|
entity_id = metadata["norad_cat_id"].as_string()
|
|
else:
|
|
group = func.coalesce(
|
|
metadata["operator"].as_string(), metadata["organization"].as_string(), ""
|
|
)
|
|
entity_id = record.source + ":" + record.source_id
|
|
return select(
|
|
record.name.label("name"),
|
|
cast(entity_id, String).label("entity_id"),
|
|
model.label("model"),
|
|
group.label("group"),
|
|
category.label("category"),
|
|
).where(
|
|
(
|
|
compute_record_filter(record)
|
|
if entity_type == "compute_center"
|
|
else record.source.in_(SOURCES[entity_type])
|
|
),
|
|
record.is_current.is_(True),
|
|
record.deleted_at.is_(None),
|
|
metadata["anonymous"].as_boolean().is_not(True),
|
|
)
|
|
|
|
|
|
def target_query(entity_type: EntityType):
|
|
if entity_type in SOURCES:
|
|
return collected_query(entity_type)
|
|
if entity_type == "vessel":
|
|
model = VesselCurrentState
|
|
identity, name, group, category = model.mmsi, model.name, model.flag, model.vessel_type_name
|
|
conditions = []
|
|
elif entity_type == "bgp":
|
|
model = BGPIncident
|
|
identity, name, group, category = (
|
|
model.incident_key,
|
|
model.title,
|
|
model.source,
|
|
model.incident_type,
|
|
)
|
|
conditions = []
|
|
elif entity_type == "bgp_collector":
|
|
model = BGPCollectorLocation
|
|
identity, name, group, category = (
|
|
model.collector_id,
|
|
model.collector_id,
|
|
model.operator,
|
|
literal("bgp_collector"),
|
|
)
|
|
conditions = []
|
|
else:
|
|
model = EarthInteractable
|
|
identity, name, group, category = model.id, model.label, model.layer, model.kind
|
|
conditions = [model.is_deleted.is_(False)]
|
|
return select(
|
|
name.label("name"),
|
|
cast(identity, String).label("entity_id"),
|
|
literal("").label("model"),
|
|
func.coalesce(group, "").label("group"),
|
|
func.coalesce(category, entity_type).label("category"),
|
|
).where(*conditions)
|
|
|
|
|
|
def category_context(entity_type: EntityType) -> dict[str, str]:
|
|
return {
|
|
"entity_type": entity_type,
|
|
"entity_id": "",
|
|
"name": "",
|
|
"model": "",
|
|
"group": "",
|
|
"category": entity_type,
|
|
}
|
|
|
|
|
|
async def get_target(db: AsyncSession, entity_type: EntityType, entity_id: str) -> dict[str, str]:
|
|
if entity_type == "compute_center" and entity_id.startswith("__category__:"):
|
|
category = entity_id.partition(":")[2]
|
|
if category in COMPUTE_SITE_TYPES:
|
|
return {**category_context(entity_type), "category": category}
|
|
if entity_id == "__category__":
|
|
return category_context(entity_type)
|
|
if entity_type in SOURCES and entity_type != "satellite":
|
|
source, separator, source_id = entity_id.partition(":")
|
|
if not separator or not source or not source_id:
|
|
return category_context(entity_type)
|
|
# Match the indexed identity columns before projecting JSON metadata.
|
|
statement = collected_query(entity_type).where(
|
|
CollectedData.source == source, CollectedData.source_id == source_id
|
|
)
|
|
else:
|
|
catalog = target_query(entity_type).subquery()
|
|
statement = select(catalog).where(catalog.c.entity_id == entity_id)
|
|
row = (await db.execute(statement.limit(1))).mappings().first()
|
|
if not row:
|
|
# Old map snapshots can outlive a catalog refresh. They may use the type
|
|
# illustration, but must not claim an unverified exact-object identity.
|
|
return category_context(entity_type)
|
|
context = {key: str(value or "") for key, value in row.items()}
|
|
return {**context, "entity_type": entity_type}
|
|
|
|
|
|
async def search_targets(
|
|
db: AsyncSession, entity_type: EntityType, scope: MatchScope, query: str, limit: int
|
|
) -> list[dict[str, str]]:
|
|
catalog = target_query(entity_type).subquery()
|
|
value = catalog.c["entity_id" if scope == "object" else scope]
|
|
label = catalog.c.name if scope == "object" else value
|
|
statement = select(value.label("value"), label.label("label")).where(
|
|
value.is_not(None), value != ""
|
|
)
|
|
if query:
|
|
escaped = query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
statement = statement.where(
|
|
or_(value.ilike(f"%{escaped}%", escape="\\"), label.ilike(f"%{escaped}%", escape="\\"))
|
|
)
|
|
rows = (await db.execute(statement.distinct().order_by(label, value).limit(limit))).mappings()
|
|
items = [{"value": row["value"], "label": row["label"] or row["value"]} for row in rows]
|
|
if scope == "category" and not query:
|
|
known = {item["value"] for item in items}
|
|
if entity_type == "compute_center":
|
|
items.extend(
|
|
{"value": kind, "label": kind} for kind in COMPUTE_SITE_TYPES if kind not in known
|
|
)
|
|
items.insert(0, {"value": "*", "label": "*"})
|
|
return items
|