use std::time::Duration;
use async_trait::async_trait;
use crate::{
map_otype, wire, AliasKind, PositionMatch, PositionResolver, ResolveError, ResolvedAlias,
ResolvedIdentity, Resolver, SimbadConfig, TargetSource,
};
const MAX_RESPONSE_BYTES: u64 = 8 * 1024 * 1024;
#[derive(Debug)]
pub struct TapResolver {
client: reqwest::Client,
endpoint: url::Url,
timeout: Duration,
}
impl TapResolver {
pub fn new(config: &SimbadConfig) -> Result<Self, ResolveError> {
let endpoint = url::Url::parse(&config.endpoint).map_err(|e| {
ResolveError::Network(format!("invalid TAP endpoint {:?}: {e}", config.endpoint))
})?;
let client = reqwest::Client::builder()
.user_agent(config.user_agent.clone())
.timeout(config.timeout)
.build()
.map_err(|e| ResolveError::Network(e.to_string()))?;
Ok(Self { client, endpoint, timeout: config.timeout })
}
pub fn with_defaults() -> Result<Self, ResolveError> {
Self::new(&SimbadConfig::default())
}
async fn tap_query(&self, adql: &str) -> Result<String, ResolveError> {
tracing::debug!(query = adql, "SIMBAD TAP request");
let resp = self
.client
.get(self.endpoint.clone())
.query(&[("request", "doQuery"), ("lang", "ADQL"), ("format", "tsv"), ("query", adql)])
.send()
.await
.map_err(|e| classify_reqwest(&e, self.timeout))?;
let mut resp = resp.error_for_status().map_err(|e| classify_reqwest(&e, self.timeout))?;
if let Some(len) = resp.content_length() {
if len > MAX_RESPONSE_BYTES {
return Err(ResolveError::Parse(format!(
"SIMBAD response too large ({len} bytes > {MAX_RESPONSE_BYTES} cap)"
)));
}
}
let mut buf: Vec<u8> = Vec::new();
let mut total: u64 = 0;
while let Some(chunk) =
resp.chunk().await.map_err(|e| classify_reqwest(&e, self.timeout))?
{
total += chunk.len() as u64;
if total > MAX_RESPONSE_BYTES {
return Err(ResolveError::Parse(format!(
"SIMBAD response exceeded {MAX_RESPONSE_BYTES} byte cap"
)));
}
buf.extend_from_slice(&chunk);
}
let body = String::from_utf8_lossy(&buf).into_owned();
if is_votable_error(&body) {
return Err(ResolveError::Parse("SIMBAD returned a VOTable error".to_owned()));
}
Ok(body)
}
async fn find_objects(&self, query: &str) -> Result<Vec<BasicRow>, ResolveError> {
let collapsed = wire::collapse_spaces(query);
let mut id_forms: Vec<String> = vec![query.to_owned()];
if collapsed != query {
id_forms.push(collapsed);
}
let list = id_forms
.iter()
.map(|id| format!("'{}'", id.replace('\'', "''")))
.collect::<Vec<_>>()
.join(", ");
let q = format!(
"SELECT DISTINCT b.oid, b.main_id, b.ra, b.dec, b.otype_txt, f.V \
FROM basic AS b JOIN ident AS i ON i.oidref = b.oid \
LEFT OUTER JOIN allfluxes AS f ON f.oidref = b.oid \
WHERE i.id IN ({list}) AND b.ra IS NOT NULL AND b.dec IS NOT NULL"
);
let body = self.tap_query(&q).await?;
Ok(parse_basic_rows(&body))
}
async fn fetch_aliases(
&self,
oid: i64,
) -> Result<(Vec<ResolvedAlias>, Option<String>), ResolveError> {
let q = format!("SELECT i.id FROM ident AS i WHERE i.oidref = {oid}");
let body = self.tap_query(&q).await?;
Ok(assemble_aliases(&body))
}
}
#[async_trait]
impl Resolver for TapResolver {
async fn resolve(&self, query: &str) -> Result<ResolvedIdentity, ResolveError> {
let query = query.trim();
if query.is_empty() {
return Err(ResolveError::NotFound(String::new()));
}
let objects = self.find_objects(query).await?;
match objects.len() {
0 => Err(ResolveError::NotFound(query.to_owned())),
1 => {
let (oid, main_id, ra_deg, dec_deg, otype_raw, v_mag) =
objects.into_iter().next().expect("len == 1 checked above");
let (aliases, common_name) = self.fetch_aliases(oid).await?;
Ok(assemble_identity(
oid,
&main_id,
ra_deg,
dec_deg,
&otype_raw,
v_mag,
aliases,
common_name,
))
}
n => Err(ResolveError::Ambiguous { query: query.to_owned(), count: n }),
}
}
}
#[async_trait]
impl PositionResolver for TapResolver {
async fn resolve_position(
&self,
ra_deg: f64,
dec_deg: f64,
radius_deg: f64,
limit: usize,
) -> Result<Vec<PositionMatch>, ResolveError> {
let q = format!(
"SELECT TOP {limit} b.oid, b.main_id, b.ra, b.dec, b.otype_txt, f.V, \
DISTANCE(POINT('ICRS', b.ra, b.dec), POINT('ICRS', {ra_deg}, {dec_deg})) AS dist \
FROM basic AS b \
LEFT OUTER JOIN allfluxes AS f ON f.oidref = b.oid \
WHERE CONTAINS(POINT('ICRS', b.ra, b.dec), CIRCLE('ICRS', {ra_deg}, {dec_deg}, {radius_deg})) = 1 \
AND b.ra IS NOT NULL \
ORDER BY dist ASC"
);
let body = self.tap_query(&q).await?;
Ok(parse_position_rows(&body)
.into_iter()
.map(|(oid, main_id, ra, dec, otype_raw, v_mag, dist)| PositionMatch {
identity: assemble_identity(
oid,
&main_id,
ra,
dec,
&otype_raw,
v_mag,
Vec::new(),
None,
),
separation_deg: dist,
})
.collect())
}
}
type BasicRow = (i64, String, f64, f64, String, Option<f64>);
type PositionRow = (i64, String, f64, f64, String, Option<f64>, f64);
fn classify_reqwest(e: &reqwest::Error, timeout: Duration) -> ResolveError {
if e.is_timeout() {
ResolveError::Timeout(timeout.as_secs())
} else {
ResolveError::Network(e.to_string())
}
}
fn is_votable_error(body: &str) -> bool {
body.contains("<VOTABLE") && body.contains("ERROR")
}
fn tsv_data_lines(body: &str) -> impl Iterator<Item = &str> {
body.lines().skip(1).filter(|l| !l.trim().is_empty())
}
fn parse_basic_rows(body: &str) -> Vec<BasicRow> {
tsv_data_lines(body).filter_map(wire::parse_basic_row).collect()
}
fn parse_position_row(line: &str) -> Option<PositionRow> {
let fields: Vec<&str> = line.split('\t').collect();
if fields.len() < 7 {
return None;
}
let (oid, main_id, ra, dec, otype, v_mag) = wire::parse_basic_row(&fields[..6].join("\t"))?;
let dist: f64 = wire::unquote(fields[6]).parse().ok()?;
if !dist.is_finite() || dist < 0.0 {
return None;
}
Some((oid, main_id, ra, dec, otype, v_mag, dist))
}
fn parse_position_rows(body: &str) -> Vec<PositionRow> {
tsv_data_lines(body).filter_map(parse_position_row).collect()
}
fn assemble_aliases(body: &str) -> (Vec<ResolvedAlias>, Option<String>) {
let mut aliases: Vec<ResolvedAlias> = Vec::new();
let mut common_name: Option<String> = None;
for line in tsv_data_lines(body) {
let id_raw = wire::unquote(line);
if id_raw.is_empty() {
continue;
}
if let Some(name) = id_raw.strip_prefix("NAME ") {
let name = name.trim();
if common_name.is_none() {
common_name = Some(name.to_owned());
}
push_unique(&mut aliases, name, AliasKind::CommonName);
} else {
push_unique(&mut aliases, &wire::collapse_spaces(&id_raw), AliasKind::Designation);
}
}
(aliases, common_name)
}
#[allow(clippy::too_many_arguments)]
fn assemble_identity(
oid: i64,
main_id: &str,
ra_deg: f64,
dec_deg: f64,
otype_raw: &str,
v_mag: Option<f64>,
mut aliases: Vec<ResolvedAlias>,
common_name: Option<String>,
) -> ResolvedIdentity {
let primary_designation = wire::collapse_spaces(main_id);
push_unique(&mut aliases, &primary_designation, AliasKind::Designation);
ResolvedIdentity {
simbad_oid: Some(oid),
primary_designation,
common_name,
object_type: map_otype(otype_raw),
otype_raw: otype_raw.to_owned(),
ra_deg,
dec_deg,
v_mag,
aliases,
source: TargetSource::Resolved,
}
}
fn push_unique(out: &mut Vec<ResolvedAlias>, alias: &str, kind: AliasKind) {
if alias.is_empty() || out.iter().any(|a| a.alias == alias) {
return;
}
out.push(ResolvedAlias::new(alias, kind));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ObjectType;
const M31_BASIC_TSV: &str = "oid\tmain_id\tra\tdec\totype_txt\tV\n\
1575544\t\"M 31\"\t10.6847083\t41.26875\t\"G\"\t3.44\n";
const AMBIGUOUS_BASIC_TSV: &str = "oid\tmain_id\tra\tdec\totype_txt\tV\n\
1575544\t\"M 31\"\t10.6847083\t41.26875\t\"G\"\t3.44\n\
999999\t\"Some Other\"\t11.0\t42.0\t\"G\"\t\n";
const EMPTY_BASIC_TSV: &str = "oid\tmain_id\tra\tdec\totype_txt\tV\n";
const M31_ALIAS_TSV: &str = "id\n\
\"M 31\"\n\
\"NGC 224\"\n\
\"NAME Andromeda Galaxy\"\n\
\"NAME Andromeda Nebula\"\n";
const M31_POSITION_TSV: &str = "oid\tmain_id\tra\tdec\totype_txt\tV\tdist\n\
1575544\t\"M 31\"\t10.6847083\t41.26875\t\"G\"\t3.44\t0.001\n\
222\t\"NGC 206\"\t10.9\t40.7\t\"OpC\"\t\t0.6\n";
const VOTABLE_ERROR_BODY: &str = "<VOTABLE version=\"1.4\"><RESOURCE type=\"results\">\
<INFO name=\"QUERY_STATUS\" value=\"ERROR\">syntax error</INFO></RESOURCE></VOTABLE>";
#[test]
fn parse_basic_rows_extracts_one_object() {
let rows = parse_basic_rows(M31_BASIC_TSV);
assert_eq!(rows.len(), 1);
let (oid, main_id, ra, dec, otype, v_mag) = &rows[0];
assert_eq!(*oid, 1_575_544);
assert_eq!(main_id, "M 31");
assert!((ra - 10.684_708_3).abs() < 1e-6);
assert!((dec - 41.268_75).abs() < 1e-6);
assert_eq!(otype, "G");
assert_eq!(map_otype(otype), ObjectType::Galaxy);
assert_eq!(*v_mag, Some(3.44));
}
#[test]
fn parse_basic_rows_zero_rows_is_not_found_precondition() {
assert!(parse_basic_rows(EMPTY_BASIC_TSV).is_empty());
}
#[test]
fn parse_basic_rows_multiple_rows_is_ambiguous_precondition() {
assert_eq!(parse_basic_rows(AMBIGUOUS_BASIC_TSV).len(), 2);
}
#[test]
fn assemble_aliases_splits_names_and_designations() {
let (aliases, common_name) = assemble_aliases(M31_ALIAS_TSV);
assert_eq!(common_name.as_deref(), Some("Andromeda Galaxy"));
assert!(aliases.iter().any(|a| a.alias == "M 31" && a.kind == AliasKind::Designation));
assert!(aliases.iter().any(|a| a.alias == "NGC 224" && a.kind == AliasKind::Designation));
assert!(aliases
.iter()
.any(|a| a.alias == "Andromeda Galaxy" && a.kind == AliasKind::CommonName));
assert!(aliases
.iter()
.any(|a| a.alias == "Andromeda Nebula" && a.kind == AliasKind::CommonName));
}
#[test]
fn assemble_identity_builds_full_identity_and_dedupes_primary_alias() {
let (aliases, common_name) = assemble_aliases(M31_ALIAS_TSV);
let identity = assemble_identity(
1_575_544,
"M 31",
10.684_708_3,
41.268_75,
"G",
Some(3.44),
aliases,
common_name,
);
assert_eq!(identity.simbad_oid, Some(1_575_544));
assert_eq!(identity.primary_designation, "M 31");
assert_eq!(identity.object_type, ObjectType::Galaxy);
assert_eq!(identity.otype_raw, "G");
assert_eq!(identity.v_mag, Some(3.44));
assert_eq!(identity.common_name.as_deref(), Some("Andromeda Galaxy"));
assert_eq!(identity.source, TargetSource::Resolved);
assert_eq!(identity.aliases.iter().filter(|a| a.alias == "M 31").count(), 1);
}
#[test]
fn assemble_identity_adds_primary_designation_when_alias_list_is_empty() {
let identity = assemble_identity(42, "NGC 206", 10.9, 40.7, "OpC", None, Vec::new(), None);
assert_eq!(identity.aliases.len(), 1);
assert_eq!(identity.aliases[0].alias, "NGC 206");
assert_eq!(identity.aliases[0].kind, AliasKind::Designation);
assert_eq!(identity.object_type, ObjectType::OpenCluster);
assert_eq!(identity.v_mag, None);
}
#[test]
fn parse_position_rows_parses_distance_column_in_order() {
let rows = parse_position_rows(M31_POSITION_TSV);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].0, 1_575_544);
assert_eq!(rows[0].5, Some(3.44));
assert!((rows[0].6 - 0.001).abs() < 1e-9);
assert_eq!(rows[1].0, 222);
assert_eq!(rows[1].5, None, "NGC 206 has no V mag → empty column → None");
assert!((rows[1].6 - 0.6).abs() < 1e-9);
}
#[test]
fn is_votable_error_detects_error_body_only() {
assert!(is_votable_error(VOTABLE_ERROR_BODY));
assert!(!is_votable_error(M31_BASIC_TSV));
}
#[test]
fn push_unique_dedupes_by_display() {
let mut v = Vec::new();
push_unique(&mut v, "M 31", AliasKind::Designation);
push_unique(&mut v, "M 31", AliasKind::Designation);
push_unique(&mut v, "", AliasKind::Designation);
assert_eq!(v.len(), 1);
}
#[test]
fn resolver_builds_from_defaults() {
assert!(TapResolver::with_defaults().is_ok());
}
#[test]
fn resolver_rejects_invalid_endpoint() {
let config = SimbadConfig { endpoint: "not a url".to_owned(), ..SimbadConfig::default() };
let err = TapResolver::new(&config).unwrap_err();
assert!(matches!(err, ResolveError::Network(_)));
}
}