simbad-resolver 0.3.2

SIMBAD astronomical target resolver for Rust: resolve names, designations, and positions to canonical identities, with a pluggable redb-backed cache.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Pluggable `Cache` and `Queue` traits and their read models.
//!
//! The [`Cache`] is a durable dedup/typeahead store of canonical target
//! identities (not a TTL/eviction cache). The [`Queue`] is the pending-work
//! store the async batch resolver drains. Both are `async` and object-safe;
//! the built-in [`redb`] backend ([`redb::Store`]) serves both durable
//! (file-backed) and ephemeral (in-memory) modes, and callers may supply their
//! own.

pub mod redb;

use uuid::Uuid;

use crate::types::{ObjectType, ResolvedAlias, ResolvedIdentity, TargetSource};

// ── Read models ──────────────────────────────────────────────────────────────

/// A cached canonical target plus its aliases, as read back from a [`Cache`].
///
/// Mirrors [`ResolvedIdentity`] but additionally carries the persisted
/// [`CachedTarget::id`] and [`CachedTarget::resolved_at`].
#[derive(Clone, Debug, PartialEq)]
pub struct CachedTarget {
    /// Persisted target id (UUIDv5 derived from the caller namespace).
    pub id: Uuid,
    /// SIMBAD physical-object id (dedup key) when resolved online.
    pub simbad_oid: Option<i64>,
    /// Canonical display designation.
    pub primary_designation: String,
    /// Curated common name when one exists.
    pub common_name: Option<String>,
    /// Closed object-type classification.
    pub object_type: ObjectType,
    /// Raw SIMBAD `otype` string (escape hatch alongside `object_type`).
    pub otype_raw: String,
    /// ICRS J2000 right ascension, decimal degrees.
    pub ra_deg: f64,
    /// ICRS J2000 declination, decimal degrees.
    pub dec_deg: f64,
    /// Johnson V-band apparent magnitude (SIMBAD `allfluxes.V`) when known.
    pub v_mag: Option<f64>,
    /// Provenance of the stored identity.
    pub source: TargetSource,
    /// RFC 3339 timestamp of the last seed/resolve/override.
    pub resolved_at: String,
    /// All aliases (designations + common names + user-added).
    pub aliases: Vec<ResolvedAlias>,
}

impl CachedTarget {
    /// Build a [`ResolvedIdentity`] view of this cached target.
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, CachedTarget, ObjectType, ResolvedAlias, TargetSource};
    /// use uuid::Uuid;
    ///
    /// let target = CachedTarget {
    ///     id: Uuid::nil(),
    ///     simbad_oid: Some(1_575_544),
    ///     primary_designation: "M 31".to_owned(),
    ///     common_name: Some("Andromeda Galaxy".to_owned()),
    ///     object_type: ObjectType::Galaxy,
    ///     otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708,
    ///     dec_deg: 41.268_75,
    ///     v_mag: Some(3.44),
    ///     source: TargetSource::Resolved,
    ///     resolved_at: "2026-07-11T00:00:00Z".to_owned(),
    ///     aliases: vec![ResolvedAlias::new("NGC 224", AliasKind::Designation)],
    /// };
    /// let identity = target.to_identity();
    /// assert_eq!(identity.primary_designation, "M 31");
    /// assert_eq!(identity.aliases, target.aliases);
    /// ```
    #[must_use]
    pub fn to_identity(&self) -> ResolvedIdentity {
        ResolvedIdentity {
            simbad_oid: self.simbad_oid,
            primary_designation: self.primary_designation.clone(),
            common_name: self.common_name.clone(),
            object_type: self.object_type,
            otype_raw: self.otype_raw.clone(),
            ra_deg: self.ra_deg,
            dec_deg: self.dec_deg,
            v_mag: self.v_mag,
            aliases: self.aliases.clone(),
            source: self.source,
        }
    }

    /// This target's sky position as a typed `skymath::Equatorial` coordinate.
    ///
    /// SIMBAD coordinates are ICRS; at planning grade (≤ ~1 arcminute) ICRS is
    /// treated as J2000. The raw [`Self::ra_deg`] / [`Self::dec_deg`] fields
    /// remain the canonical storage.
    ///
    /// # Errors
    ///
    /// `skymath::Error::OutOfRange` if the stored values are outside RA
    /// `[0, 360)` / Dec `[-90, +90]` (malformed cache content).
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, CachedTarget, ObjectType, ResolvedAlias, TargetSource};
    /// use uuid::Uuid;
    ///
    /// # fn run() -> Result<(), skymath::Error> {
    /// let target = CachedTarget {
    ///     id: Uuid::nil(), simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     source: TargetSource::Resolved, resolved_at: "2026-07-11T00:00:00Z".to_owned(),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    /// };
    /// let eq = target.position()?;
    /// assert!((eq.ra().degrees() - 10.684_708).abs() < 1e-6);
    /// # Ok(()) }
    /// ```
    pub fn position(&self) -> skymath::Result<skymath::Equatorial> {
        skymath::Equatorial::j2000(
            skymath::Angle::from_degrees(self.ra_deg),
            skymath::Angle::from_degrees(self.dec_deg),
        )
    }
}

/// A single ranked typeahead hit.
#[derive(Clone, Debug, PartialEq)]
pub struct SearchHit {
    /// The matched canonical target (aliases loaded).
    pub target: CachedTarget,
    /// The display form of the alias that matched.
    pub matched_alias: String,
    /// Rank bucket: `0` exact, `1` prefix, `2` substring, `3` fuzzy.
    pub rank: u8,
}

/// Rank bucket for an exact normalized-alias match.
pub const RANK_EXACT: u8 = 0;
/// Rank bucket for a prefix match.
pub const RANK_PREFIX: u8 = 1;
/// Rank bucket for a substring match.
pub const RANK_SUBSTRING: u8 = 2;
/// Rank bucket for a fuzzy (token-set similarity) match.
///
/// Only produced by the facade [`crate::SimbadResolver::search`] when fuzzy
/// matching is enabled via [`crate::ResolverConfig::with_fuzzy`]; the
/// [`Cache::search`] trait method itself never returns this rank.
pub const RANK_FUZZY: u8 = 3;

/// Outcome of a [`Cache::upsert`] call.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UpsertOutcome {
    /// A new row was inserted.
    Inserted,
    /// An existing row (matched by oid or derived id) was updated.
    Updated,
    /// Skipped: an existing `user-override` row takes precedence.
    SkippedUserOverride,
}

/// State of a queued batch item.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PendingState {
    /// Awaiting resolution (or a retry after a transient failure).
    Pending,
    /// Resolved to a canonical target.
    Resolved,
    /// A genuine content miss (unknown/ambiguous).
    Unresolved,
}

impl PendingState {
    /// The wire/DB string.
    ///
    /// ```
    /// use simbad_resolver::PendingState;
    ///
    /// assert_eq!(PendingState::Unresolved.as_wire(), "unresolved");
    /// ```
    #[must_use]
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Resolved => "resolved",
            Self::Unresolved => "unresolved",
        }
    }

    /// Parse a wire/DB string; unknown → `None`.
    ///
    /// ```
    /// use simbad_resolver::PendingState;
    ///
    /// assert_eq!(PendingState::from_wire("resolved"), Some(PendingState::Resolved));
    /// assert_eq!(PendingState::from_wire("bogus"), None);
    /// ```
    #[must_use]
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "pending" => Some(Self::Pending),
            "resolved" => Some(Self::Resolved),
            "unresolved" => Some(Self::Unresolved),
            _ => None,
        }
    }
}

/// One queued batch item (read model for a [`Queue`]).
#[derive(Clone, Debug, PartialEq)]
pub struct PendingItem {
    /// Opaque caller id (the queue key).
    pub id: String,
    /// Raw identifier to resolve.
    pub query: String,
    /// Current state.
    pub state: PendingState,
    /// Attempt counter (incremented only on content misses).
    pub attempts: i64,
    /// Resolved canonical-target id, when resolved.
    pub target_id: Option<Uuid>,
}

// ── Errors ───────────────────────────────────────────────────────────────────

/// Error type for [`Cache`] operations.
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    /// Underlying backend failure (DB error, etc.).
    #[error("cache backend error: {0}")]
    Backend(String),
    /// A stored id was not a valid UUID.
    #[error("invalid stored uuid '{0}': {1}")]
    InvalidUuid(String, uuid::Error),
    /// A stored enum value was outside its closed set.
    #[error("invalid stored enum value: '{0}'")]
    InvalidEnum(String),
}

/// Error type for [`Queue`] operations.
#[derive(Debug, thiserror::Error)]
pub enum QueueError {
    /// Underlying backend failure.
    #[error("queue backend error: {0}")]
    Backend(String),
    /// A stored id was not a valid UUID.
    #[error("invalid stored uuid '{0}': {1}")]
    InvalidUuid(String, uuid::Error),
    /// A stored state value was outside its closed set.
    #[error("invalid stored state: '{0}'")]
    InvalidState(String),
}

// ── Cache trait ──────────────────────────────────────────────────────────────

/// The pluggable identity store.
///
/// Implementations MUST honour dedup + source precedence in [`Cache::upsert`]:
/// match an existing row by `simbad_oid` when `Some`, else by the caller's
/// designation-derived id ([`crate::identity::target_id_from_designation`]); a
/// write proceeds iff `incoming.source.may_overwrite(existing.source)` (a
/// `user-override` row is sticky). Aliases are rewritten wholesale on update.
#[async_trait::async_trait]
pub trait Cache: Send + Sync {
    /// Read a cached target by its persisted id.
    ///
    /// These trait-method examples all use the built-in [`crate::Store`]'s
    /// in-memory [`Cache`] (`RedbCache`) — local redb access, no network.
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// let (id, _) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// let target = store.cache().get_by_id(id).await?.expect("just inserted");
    /// assert_eq!(target.primary_designation, "M 31");
    /// # Ok(()) }
    /// ```
    async fn get_by_id(&self, id: Uuid) -> Result<Option<CachedTarget>, CacheError>;

    /// Read a cached target by its SIMBAD physical-object id.
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// let target = store.cache().get_by_simbad_oid(1_575_544).await?.expect("dedup key matches");
    /// assert_eq!(target.primary_designation, "M 31");
    /// # Ok(()) }
    /// ```
    async fn get_by_simbad_oid(&self, oid: i64) -> Result<Option<CachedTarget>, CacheError>;

    /// Read a cached target by an exact normalized alias (normalize the query first).
    ///
    /// ```
    /// use simbad_resolver::{
    ///     normalize::normalize, AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity,
    ///     Store, TargetSource,
    /// };
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// let target = store.cache().get_by_normalized(&normalize("M31")).await?.expect("normalized match");
    /// assert_eq!(target.primary_designation, "M 31");
    /// # Ok(()) }
    /// ```
    async fn get_by_normalized(&self, normalized: &str)
        -> Result<Option<CachedTarget>, CacheError>;

    /// Ranked typeahead search over aliases: exact > prefix > substring, deduped
    /// to one hit per target (best rank wins, ties → shortest alias), capped to
    /// `limit`. Local-only, no network. A blank query or `limit == 0` → empty.
    ///
    /// See [`crate::SimbadResolver::search`] for the facade wrapper that also
    /// adds a fuzzy tier on top of this.
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// let hits = store.cache().search("M 3", 5).await?; // prefix match
    /// assert_eq!(hits[0].target.primary_designation, "M 31");
    /// # Ok(()) }
    /// ```
    async fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>, CacheError>;

    /// Upsert an identity (and its aliases) with dedup + precedence. `namespace`
    /// is the caller's id namespace for the designation-derived fallback id.
    ///
    /// ```
    /// use simbad_resolver::{
    ///     AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource,
    ///     UpsertOutcome,
    /// };
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// let (_id, outcome) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// assert_eq!(outcome, UpsertOutcome::Inserted);
    /// # Ok(()) }
    /// ```
    async fn upsert(
        &self,
        identity: &ResolvedIdentity,
        namespace: &Uuid,
    ) -> Result<(Uuid, UpsertOutcome), CacheError>;

    /// Upsert many identities under one `namespace`, in order, with the exact
    /// same per-entry dedup + precedence semantics as calling [`Cache::upsert`]
    /// once per identity (including [`UpsertOutcome::SkippedUserOverride`] and
    /// dedup against earlier entries of the same batch).
    ///
    /// The default implementation simply loops over [`Cache::upsert`]. Warming
    /// a large seed set (thousands of entries) through that default costs one
    /// backend commit per entry; the built-in redb backend
    /// ([`crate::cache::redb::RedbCache`]) overrides this to do the whole batch
    /// in a single write transaction instead.
    ///
    /// ```
    /// use simbad_resolver::{
    ///     AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource,
    ///     UpsertOutcome,
    /// };
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// let results = store.cache().upsert_batch(&[m31], &uuid::Uuid::nil()).await?;
    /// assert_eq!(results.len(), 1);
    /// assert_eq!(results[0].1, UpsertOutcome::Inserted);
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns the first [`CacheError`] hit; entries already written before
    /// that point in the batch remain committed (the default, per-item
    /// implementation) or are rolled back together (the redb override, which
    /// commits the whole batch atomically).
    async fn upsert_batch(
        &self,
        identities: &[ResolvedIdentity],
        namespace: &Uuid,
    ) -> Result<Vec<(Uuid, UpsertOutcome)>, CacheError> {
        let mut results = Vec::with_capacity(identities.len());
        for identity in identities {
            results.push(self.upsert(identity, namespace).await?);
        }
        Ok(results)
    }

    /// Add a user alias (`kind = 'user'`). Returns `true` if newly inserted,
    /// `false` if it already existed (idempotent).
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// let (id, _) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// assert!(store.cache().add_user_alias(id, "My Andromeda").await?);
    /// assert!(!store.cache().add_user_alias(id, "My Andromeda").await?, "idempotent");
    /// # Ok(()) }
    /// ```
    async fn add_user_alias(&self, target_id: Uuid, alias: &str) -> Result<bool, CacheError>;

    /// Remove a user alias by id, only if its `kind = 'user'`. Returns whether a
    /// row was removed.
    ///
    /// The alias id is opaque and backend-assigned (not exposed by
    /// [`CachedTarget`]/[`ResolvedAlias`] directly), so this trait-level example
    /// only demonstrates the no-op case on an unknown id — see
    /// `crate::cache::redb` tests for a full add/remove round trip.
    ///
    /// ```
    /// use simbad_resolver::{Cache, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// assert!(!store.cache().remove_user_alias("does-not-exist").await?);
    /// # Ok(()) }
    /// ```
    async fn remove_user_alias(&self, alias_id: &str) -> Result<bool, CacheError>;

    /// List all cached targets (ordered by `primary_designation`).
    ///
    /// ```
    /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
    /// let store = Store::in_memory()?;
    /// assert!(store.cache().list().await?.is_empty());
    /// let m31 = ResolvedIdentity {
    ///     simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
    ///     common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
    ///     ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
    ///     source: TargetSource::Seed,
    /// };
    /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
    /// assert_eq!(store.cache().list().await?.len(), 1);
    /// # Ok(()) }
    /// ```
    async fn list(&self) -> Result<Vec<CachedTarget>, CacheError>;
}

// ── Queue trait ──────────────────────────────────────────────────────────────

/// The pluggable pending-work store for the async batch resolver.
///
/// Transient failures (`ResolveError::is_transient`) → [`Queue::release`] (stay
/// pending, attempts unchanged). Content misses → [`Queue::mark_unresolved`]
/// (attempts += 1).
#[async_trait::async_trait]
pub trait Queue: Send + Sync {
    /// Enqueue an item (idempotent by `id`); a no-op if `id` already present.
    ///
    /// These trait-method examples all use the built-in [`crate::Store`]'s
    /// in-memory [`Queue`] (`RedbQueue`) — local redb access, no network.
    ///
    /// ```
    /// use simbad_resolver::{Queue, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "M31").await?;
    /// store.queue().enqueue("job-1", "M31").await?; // idempotent
    /// assert_eq!(store.queue().pending_count().await?, 1);
    /// # Ok(()) }
    /// ```
    async fn enqueue(&self, id: &str, query: &str) -> Result<(), QueueError>;

    /// Claim up to `n` pending items for processing (approximately FIFO).
    ///
    /// ```
    /// use simbad_resolver::{PendingState, Queue, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "M31").await?;
    /// let claimed = store.queue().claim_pending(8).await?;
    /// assert_eq!(claimed.len(), 1);
    /// assert_eq!(claimed[0].state, PendingState::Pending);
    /// # Ok(()) }
    /// ```
    async fn claim_pending(&self, n: usize) -> Result<Vec<PendingItem>, QueueError>;

    /// Mark an item resolved and bind its target (attempts unchanged).
    ///
    /// ```
    /// use simbad_resolver::{PendingState, Queue, Store};
    /// use uuid::Uuid;
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "M31").await?;
    /// store.queue().mark_resolved("job-1", Uuid::nil()).await?;
    /// let item = store.queue().get("job-1").await?.expect("still present");
    /// assert_eq!(item.state, PendingState::Resolved);
    /// assert_eq!(item.target_id, Some(Uuid::nil()));
    /// # Ok(()) }
    /// ```
    async fn mark_resolved(&self, id: &str, target_id: Uuid) -> Result<(), QueueError>;

    /// Mark an item unresolved (content miss); attempts += 1.
    ///
    /// ```
    /// use simbad_resolver::{PendingState, Queue, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "does-not-exist").await?;
    /// store.queue().mark_unresolved("job-1").await?;
    /// let item = store.queue().get("job-1").await?.expect("still present");
    /// assert_eq!(item.state, PendingState::Unresolved);
    /// assert_eq!(item.attempts, 1);
    /// # Ok(()) }
    /// ```
    async fn mark_unresolved(&self, id: &str) -> Result<(), QueueError>;

    /// Release a claimed item back to pending after a transient failure
    /// (attempts unchanged).
    ///
    /// ```
    /// use simbad_resolver::{PendingState, Queue, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "M31").await?;
    /// store.queue().claim_pending(8).await?; // simulate a claim
    /// store.queue().release("job-1").await?; // ... then a transient failure
    /// let item = store.queue().get("job-1").await?.expect("still present");
    /// assert_eq!(item.state, PendingState::Pending);
    /// assert_eq!(item.attempts, 0, "transient failures don't spend the attempt budget");
    /// # Ok(()) }
    /// ```
    async fn release(&self, id: &str) -> Result<(), QueueError>;

    /// Read a single item by id.
    ///
    /// ```
    /// use simbad_resolver::{Queue, Store};
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// assert!(store.queue().get("job-1").await?.is_none());
    /// store.queue().enqueue("job-1", "M31").await?;
    /// assert_eq!(store.queue().get("job-1").await?.unwrap().query, "M31");
    /// # Ok(()) }
    /// ```
    async fn get(&self, id: &str) -> Result<Option<PendingItem>, QueueError>;

    /// Count items still `pending`.
    ///
    /// ```
    /// use simbad_resolver::{Queue, Store};
    /// use uuid::Uuid;
    ///
    /// # async fn run() -> Result<(), simbad_resolver::Error> {
    /// let store = Store::in_memory()?;
    /// store.queue().enqueue("job-1", "M31").await?;
    /// store.queue().enqueue("job-2", "M101").await?;
    /// store.queue().mark_resolved("job-1", Uuid::nil()).await?;
    /// assert_eq!(store.queue().pending_count().await?, 1);
    /// # Ok(()) }
    /// ```
    async fn pending_count(&self) -> Result<usize, QueueError>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::AliasKind;

    #[test]
    fn pending_state_wire_round_trips() {
        for st in [PendingState::Pending, PendingState::Resolved, PendingState::Unresolved] {
            assert_eq!(PendingState::from_wire(st.as_wire()), Some(st));
        }
        assert_eq!(PendingState::Pending.as_wire(), "pending");
        assert_eq!(PendingState::Resolved.as_wire(), "resolved");
        assert_eq!(PendingState::Unresolved.as_wire(), "unresolved");
        assert_eq!(PendingState::from_wire("bogus"), None);
        assert_eq!(PendingState::from_wire(""), None);
    }

    #[test]
    fn cached_target_to_identity_preserves_the_identity_fields() {
        let target = CachedTarget {
            id: Uuid::nil(),
            simbad_oid: Some(1_575_544),
            primary_designation: "M 31".to_owned(),
            common_name: Some("Andromeda Galaxy".to_owned()),
            object_type: ObjectType::Galaxy,
            otype_raw: "G".to_owned(),
            ra_deg: 10.684_708,
            dec_deg: 41.268_75,
            v_mag: Some(3.44),
            source: TargetSource::Resolved,
            resolved_at: "2026-07-11T00:00:00Z".to_owned(),
            aliases: vec![ResolvedAlias::new("NGC 224", AliasKind::Designation)],
        };

        let identity = target.to_identity();
        assert_eq!(identity.simbad_oid, Some(1_575_544));
        assert_eq!(identity.primary_designation, "M 31");
        assert_eq!(identity.common_name.as_deref(), Some("Andromeda Galaxy"));
        assert_eq!(identity.object_type, ObjectType::Galaxy);
        assert_eq!(identity.otype_raw, "G");
        assert_eq!(identity.v_mag, Some(3.44));
        assert!((identity.ra_deg - 10.684_708).abs() < f64::EPSILON);
        assert_eq!(identity.source, TargetSource::Resolved);
        assert_eq!(identity.aliases, target.aliases);
    }
}