simbad_resolver/cache/mod.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Pluggable `Cache` and `Queue` traits and their read models.
6//!
7//! The [`Cache`] is a durable dedup/typeahead store of canonical target
8//! identities (not a TTL/eviction cache). The [`Queue`] is the pending-work
9//! store the async batch resolver drains. Both are `async` and object-safe;
10//! the built-in [`redb`] backend ([`redb::Store`]) serves both durable
11//! (file-backed) and ephemeral (in-memory) modes, and callers may supply their
12//! own.
13
14pub mod redb;
15
16use uuid::Uuid;
17
18use crate::types::{ObjectType, ResolvedAlias, ResolvedIdentity, TargetSource};
19
20// ── Read models ──────────────────────────────────────────────────────────────
21
22/// A cached canonical target plus its aliases, as read back from a [`Cache`].
23///
24/// Mirrors [`ResolvedIdentity`] but additionally carries the persisted
25/// [`CachedTarget::id`] and [`CachedTarget::resolved_at`].
26#[derive(Clone, Debug, PartialEq)]
27pub struct CachedTarget {
28 /// Persisted target id (UUIDv5 derived from the caller namespace).
29 pub id: Uuid,
30 /// SIMBAD physical-object id (dedup key) when resolved online.
31 pub simbad_oid: Option<i64>,
32 /// Canonical display designation.
33 pub primary_designation: String,
34 /// Curated common name when one exists.
35 pub common_name: Option<String>,
36 /// Closed object-type classification.
37 pub object_type: ObjectType,
38 /// Raw SIMBAD `otype` string (escape hatch alongside `object_type`).
39 pub otype_raw: String,
40 /// ICRS J2000 right ascension, decimal degrees.
41 pub ra_deg: f64,
42 /// ICRS J2000 declination, decimal degrees.
43 pub dec_deg: f64,
44 /// Johnson V-band apparent magnitude (SIMBAD `allfluxes.V`) when known.
45 pub v_mag: Option<f64>,
46 /// Provenance of the stored identity.
47 pub source: TargetSource,
48 /// RFC 3339 timestamp of the last seed/resolve/override.
49 pub resolved_at: String,
50 /// All aliases (designations + common names + user-added).
51 pub aliases: Vec<ResolvedAlias>,
52}
53
54impl CachedTarget {
55 /// Build a [`ResolvedIdentity`] view of this cached target.
56 ///
57 /// ```
58 /// use simbad_resolver::{AliasKind, CachedTarget, ObjectType, ResolvedAlias, TargetSource};
59 /// use uuid::Uuid;
60 ///
61 /// let target = CachedTarget {
62 /// id: Uuid::nil(),
63 /// simbad_oid: Some(1_575_544),
64 /// primary_designation: "M 31".to_owned(),
65 /// common_name: Some("Andromeda Galaxy".to_owned()),
66 /// object_type: ObjectType::Galaxy,
67 /// otype_raw: "G".to_owned(),
68 /// ra_deg: 10.684_708,
69 /// dec_deg: 41.268_75,
70 /// v_mag: Some(3.44),
71 /// source: TargetSource::Resolved,
72 /// resolved_at: "2026-07-11T00:00:00Z".to_owned(),
73 /// aliases: vec![ResolvedAlias::new("NGC 224", AliasKind::Designation)],
74 /// };
75 /// let identity = target.to_identity();
76 /// assert_eq!(identity.primary_designation, "M 31");
77 /// assert_eq!(identity.aliases, target.aliases);
78 /// ```
79 #[must_use]
80 pub fn to_identity(&self) -> ResolvedIdentity {
81 ResolvedIdentity {
82 simbad_oid: self.simbad_oid,
83 primary_designation: self.primary_designation.clone(),
84 common_name: self.common_name.clone(),
85 object_type: self.object_type,
86 otype_raw: self.otype_raw.clone(),
87 ra_deg: self.ra_deg,
88 dec_deg: self.dec_deg,
89 v_mag: self.v_mag,
90 aliases: self.aliases.clone(),
91 source: self.source,
92 }
93 }
94
95 /// This target's sky position as a typed `skymath::Equatorial` coordinate.
96 ///
97 /// SIMBAD coordinates are ICRS; at planning grade (≤ ~1 arcminute) ICRS is
98 /// treated as J2000. The raw [`Self::ra_deg`] / [`Self::dec_deg`] fields
99 /// remain the canonical storage.
100 ///
101 /// # Errors
102 ///
103 /// `skymath::Error::OutOfRange` if the stored values are outside RA
104 /// `[0, 360)` / Dec `[-90, +90]` (malformed cache content).
105 ///
106 /// ```
107 /// use simbad_resolver::{AliasKind, CachedTarget, ObjectType, ResolvedAlias, TargetSource};
108 /// use uuid::Uuid;
109 ///
110 /// # fn run() -> Result<(), skymath::Error> {
111 /// let target = CachedTarget {
112 /// id: Uuid::nil(), simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
113 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
114 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
115 /// source: TargetSource::Resolved, resolved_at: "2026-07-11T00:00:00Z".to_owned(),
116 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
117 /// };
118 /// let eq = target.position()?;
119 /// assert!((eq.ra().degrees() - 10.684_708).abs() < 1e-6);
120 /// # Ok(()) }
121 /// ```
122 pub fn position(&self) -> skymath::Result<skymath::Equatorial> {
123 skymath::Equatorial::j2000(
124 skymath::Angle::from_degrees(self.ra_deg),
125 skymath::Angle::from_degrees(self.dec_deg),
126 )
127 }
128}
129
130/// A single ranked typeahead hit.
131#[derive(Clone, Debug, PartialEq)]
132pub struct SearchHit {
133 /// The matched canonical target (aliases loaded).
134 pub target: CachedTarget,
135 /// The display form of the alias that matched.
136 pub matched_alias: String,
137 /// Rank bucket: `0` exact, `1` prefix, `2` substring, `3` fuzzy.
138 pub rank: u8,
139}
140
141/// Rank bucket for an exact normalized-alias match.
142pub const RANK_EXACT: u8 = 0;
143/// Rank bucket for a prefix match.
144pub const RANK_PREFIX: u8 = 1;
145/// Rank bucket for a substring match.
146pub const RANK_SUBSTRING: u8 = 2;
147/// Rank bucket for a fuzzy (token-set similarity) match.
148///
149/// Only produced by the facade [`crate::SimbadResolver::search`] when fuzzy
150/// matching is enabled via [`crate::ResolverConfig::with_fuzzy`]; the
151/// [`Cache::search`] trait method itself never returns this rank.
152pub const RANK_FUZZY: u8 = 3;
153
154/// Outcome of a [`Cache::upsert`] call.
155#[derive(Clone, Copy, Debug, Eq, PartialEq)]
156pub enum UpsertOutcome {
157 /// A new row was inserted.
158 Inserted,
159 /// An existing row (matched by oid or derived id) was updated.
160 Updated,
161 /// Skipped: an existing `user-override` row takes precedence.
162 SkippedUserOverride,
163}
164
165/// State of a queued batch item.
166#[derive(Clone, Copy, Debug, Eq, PartialEq)]
167pub enum PendingState {
168 /// Awaiting resolution (or a retry after a transient failure).
169 Pending,
170 /// Resolved to a canonical target.
171 Resolved,
172 /// A genuine content miss (unknown/ambiguous).
173 Unresolved,
174}
175
176impl PendingState {
177 /// The wire/DB string.
178 ///
179 /// ```
180 /// use simbad_resolver::PendingState;
181 ///
182 /// assert_eq!(PendingState::Unresolved.as_wire(), "unresolved");
183 /// ```
184 #[must_use]
185 pub fn as_wire(self) -> &'static str {
186 match self {
187 Self::Pending => "pending",
188 Self::Resolved => "resolved",
189 Self::Unresolved => "unresolved",
190 }
191 }
192
193 /// Parse a wire/DB string; unknown → `None`.
194 ///
195 /// ```
196 /// use simbad_resolver::PendingState;
197 ///
198 /// assert_eq!(PendingState::from_wire("resolved"), Some(PendingState::Resolved));
199 /// assert_eq!(PendingState::from_wire("bogus"), None);
200 /// ```
201 #[must_use]
202 pub fn from_wire(s: &str) -> Option<Self> {
203 match s {
204 "pending" => Some(Self::Pending),
205 "resolved" => Some(Self::Resolved),
206 "unresolved" => Some(Self::Unresolved),
207 _ => None,
208 }
209 }
210}
211
212/// One queued batch item (read model for a [`Queue`]).
213#[derive(Clone, Debug, PartialEq)]
214pub struct PendingItem {
215 /// Opaque caller id (the queue key).
216 pub id: String,
217 /// Raw identifier to resolve.
218 pub query: String,
219 /// Current state.
220 pub state: PendingState,
221 /// Attempt counter (incremented only on content misses).
222 pub attempts: i64,
223 /// Resolved canonical-target id, when resolved.
224 pub target_id: Option<Uuid>,
225}
226
227// ── Errors ───────────────────────────────────────────────────────────────────
228
229/// Error type for [`Cache`] operations.
230#[derive(Debug, thiserror::Error)]
231pub enum CacheError {
232 /// Underlying backend failure (DB error, etc.).
233 #[error("cache backend error: {0}")]
234 Backend(String),
235 /// A stored id was not a valid UUID.
236 #[error("invalid stored uuid '{0}': {1}")]
237 InvalidUuid(String, uuid::Error),
238 /// A stored enum value was outside its closed set.
239 #[error("invalid stored enum value: '{0}'")]
240 InvalidEnum(String),
241}
242
243/// Error type for [`Queue`] operations.
244#[derive(Debug, thiserror::Error)]
245pub enum QueueError {
246 /// Underlying backend failure.
247 #[error("queue backend error: {0}")]
248 Backend(String),
249 /// A stored id was not a valid UUID.
250 #[error("invalid stored uuid '{0}': {1}")]
251 InvalidUuid(String, uuid::Error),
252 /// A stored state value was outside its closed set.
253 #[error("invalid stored state: '{0}'")]
254 InvalidState(String),
255}
256
257// ── Cache trait ──────────────────────────────────────────────────────────────
258
259/// The pluggable identity store.
260///
261/// Implementations MUST honour dedup + source precedence in [`Cache::upsert`]:
262/// match an existing row by `simbad_oid` when `Some`, else by the caller's
263/// designation-derived id ([`crate::identity::target_id_from_designation`]); a
264/// write proceeds iff `incoming.source.may_overwrite(existing.source)` (a
265/// `user-override` row is sticky). Aliases are rewritten wholesale on update.
266#[async_trait::async_trait]
267pub trait Cache: Send + Sync {
268 /// Read a cached target by its persisted id.
269 ///
270 /// These trait-method examples all use the built-in [`crate::Store`]'s
271 /// in-memory [`Cache`] (`RedbCache`) — local redb access, no network.
272 ///
273 /// ```
274 /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
275 ///
276 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
277 /// let store = Store::in_memory()?;
278 /// let m31 = ResolvedIdentity {
279 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
280 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
281 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
282 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
283 /// source: TargetSource::Seed,
284 /// };
285 /// let (id, _) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
286 /// let target = store.cache().get_by_id(id).await?.expect("just inserted");
287 /// assert_eq!(target.primary_designation, "M 31");
288 /// # Ok(()) }
289 /// ```
290 async fn get_by_id(&self, id: Uuid) -> Result<Option<CachedTarget>, CacheError>;
291
292 /// Read a cached target by its SIMBAD physical-object id.
293 ///
294 /// ```
295 /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
296 ///
297 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
298 /// let store = Store::in_memory()?;
299 /// let m31 = ResolvedIdentity {
300 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
301 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
302 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
303 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
304 /// source: TargetSource::Seed,
305 /// };
306 /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
307 /// let target = store.cache().get_by_simbad_oid(1_575_544).await?.expect("dedup key matches");
308 /// assert_eq!(target.primary_designation, "M 31");
309 /// # Ok(()) }
310 /// ```
311 async fn get_by_simbad_oid(&self, oid: i64) -> Result<Option<CachedTarget>, CacheError>;
312
313 /// Read a cached target by an exact normalized alias (normalize the query first).
314 ///
315 /// ```
316 /// use simbad_resolver::{
317 /// normalize::normalize, AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity,
318 /// Store, TargetSource,
319 /// };
320 ///
321 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
322 /// let store = Store::in_memory()?;
323 /// let m31 = ResolvedIdentity {
324 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
325 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
326 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
327 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
328 /// source: TargetSource::Seed,
329 /// };
330 /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
331 /// let target = store.cache().get_by_normalized(&normalize("M31")).await?.expect("normalized match");
332 /// assert_eq!(target.primary_designation, "M 31");
333 /// # Ok(()) }
334 /// ```
335 async fn get_by_normalized(&self, normalized: &str)
336 -> Result<Option<CachedTarget>, CacheError>;
337
338 /// Ranked typeahead search over aliases: exact > prefix > substring, deduped
339 /// to one hit per target (best rank wins, ties → shortest alias), capped to
340 /// `limit`. Local-only, no network. A blank query or `limit == 0` → empty.
341 ///
342 /// See [`crate::SimbadResolver::search`] for the facade wrapper that also
343 /// adds a fuzzy tier on top of this.
344 ///
345 /// ```
346 /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
347 ///
348 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
349 /// let store = Store::in_memory()?;
350 /// let m31 = ResolvedIdentity {
351 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
352 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
353 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
354 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
355 /// source: TargetSource::Seed,
356 /// };
357 /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
358 /// let hits = store.cache().search("M 3", 5).await?; // prefix match
359 /// assert_eq!(hits[0].target.primary_designation, "M 31");
360 /// # Ok(()) }
361 /// ```
362 async fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>, CacheError>;
363
364 /// Upsert an identity (and its aliases) with dedup + precedence. `namespace`
365 /// is the caller's id namespace for the designation-derived fallback id.
366 ///
367 /// ```
368 /// use simbad_resolver::{
369 /// AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource,
370 /// UpsertOutcome,
371 /// };
372 ///
373 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
374 /// let store = Store::in_memory()?;
375 /// let m31 = ResolvedIdentity {
376 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
377 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
378 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
379 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
380 /// source: TargetSource::Seed,
381 /// };
382 /// let (_id, outcome) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
383 /// assert_eq!(outcome, UpsertOutcome::Inserted);
384 /// # Ok(()) }
385 /// ```
386 async fn upsert(
387 &self,
388 identity: &ResolvedIdentity,
389 namespace: &Uuid,
390 ) -> Result<(Uuid, UpsertOutcome), CacheError>;
391
392 /// Upsert many identities under one `namespace`, in order, with the exact
393 /// same per-entry dedup + precedence semantics as calling [`Cache::upsert`]
394 /// once per identity (including [`UpsertOutcome::SkippedUserOverride`] and
395 /// dedup against earlier entries of the same batch).
396 ///
397 /// The default implementation simply loops over [`Cache::upsert`]. Warming
398 /// a large seed set (thousands of entries) through that default costs one
399 /// backend commit per entry; the built-in redb backend
400 /// ([`crate::cache::redb::RedbCache`]) overrides this to do the whole batch
401 /// in a single write transaction instead.
402 ///
403 /// ```
404 /// use simbad_resolver::{
405 /// AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource,
406 /// UpsertOutcome,
407 /// };
408 ///
409 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
410 /// let store = Store::in_memory()?;
411 /// let m31 = ResolvedIdentity {
412 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
413 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
414 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
415 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
416 /// source: TargetSource::Seed,
417 /// };
418 /// let results = store.cache().upsert_batch(&[m31], &uuid::Uuid::nil()).await?;
419 /// assert_eq!(results.len(), 1);
420 /// assert_eq!(results[0].1, UpsertOutcome::Inserted);
421 /// # Ok(()) }
422 /// ```
423 ///
424 /// # Errors
425 ///
426 /// Returns the first [`CacheError`] hit; entries already written before
427 /// that point in the batch remain committed (the default, per-item
428 /// implementation) or are rolled back together (the redb override, which
429 /// commits the whole batch atomically).
430 async fn upsert_batch(
431 &self,
432 identities: &[ResolvedIdentity],
433 namespace: &Uuid,
434 ) -> Result<Vec<(Uuid, UpsertOutcome)>, CacheError> {
435 let mut results = Vec::with_capacity(identities.len());
436 for identity in identities {
437 results.push(self.upsert(identity, namespace).await?);
438 }
439 Ok(results)
440 }
441
442 /// Add a user alias (`kind = 'user'`). Returns `true` if newly inserted,
443 /// `false` if it already existed (idempotent).
444 ///
445 /// ```
446 /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
447 ///
448 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
449 /// let store = Store::in_memory()?;
450 /// let m31 = ResolvedIdentity {
451 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
452 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
453 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
454 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
455 /// source: TargetSource::Seed,
456 /// };
457 /// let (id, _) = store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
458 /// assert!(store.cache().add_user_alias(id, "My Andromeda").await?);
459 /// assert!(!store.cache().add_user_alias(id, "My Andromeda").await?, "idempotent");
460 /// # Ok(()) }
461 /// ```
462 async fn add_user_alias(&self, target_id: Uuid, alias: &str) -> Result<bool, CacheError>;
463
464 /// Remove a user alias by id, only if its `kind = 'user'`. Returns whether a
465 /// row was removed.
466 ///
467 /// The alias id is opaque and backend-assigned (not exposed by
468 /// [`CachedTarget`]/[`ResolvedAlias`] directly), so this trait-level example
469 /// only demonstrates the no-op case on an unknown id — see
470 /// `crate::cache::redb` tests for a full add/remove round trip.
471 ///
472 /// ```
473 /// use simbad_resolver::{Cache, Store};
474 ///
475 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
476 /// let store = Store::in_memory()?;
477 /// assert!(!store.cache().remove_user_alias("does-not-exist").await?);
478 /// # Ok(()) }
479 /// ```
480 async fn remove_user_alias(&self, alias_id: &str) -> Result<bool, CacheError>;
481
482 /// List all cached targets (ordered by `primary_designation`).
483 ///
484 /// ```
485 /// use simbad_resolver::{AliasKind, Cache, ObjectType, ResolvedAlias, ResolvedIdentity, Store, TargetSource};
486 ///
487 /// # async fn run() -> Result<(), simbad_resolver::CacheError> {
488 /// let store = Store::in_memory()?;
489 /// assert!(store.cache().list().await?.is_empty());
490 /// let m31 = ResolvedIdentity {
491 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
492 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
493 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
494 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
495 /// source: TargetSource::Seed,
496 /// };
497 /// store.cache().upsert(&m31, &uuid::Uuid::nil()).await?;
498 /// assert_eq!(store.cache().list().await?.len(), 1);
499 /// # Ok(()) }
500 /// ```
501 async fn list(&self) -> Result<Vec<CachedTarget>, CacheError>;
502}
503
504// ── Queue trait ──────────────────────────────────────────────────────────────
505
506/// The pluggable pending-work store for the async batch resolver.
507///
508/// Transient failures (`ResolveError::is_transient`) → [`Queue::release`] (stay
509/// pending, attempts unchanged). Content misses → [`Queue::mark_unresolved`]
510/// (attempts += 1).
511#[async_trait::async_trait]
512pub trait Queue: Send + Sync {
513 /// Enqueue an item (idempotent by `id`); a no-op if `id` already present.
514 ///
515 /// These trait-method examples all use the built-in [`crate::Store`]'s
516 /// in-memory [`Queue`] (`RedbQueue`) — local redb access, no network.
517 ///
518 /// ```
519 /// use simbad_resolver::{Queue, Store};
520 ///
521 /// # async fn run() -> Result<(), simbad_resolver::Error> {
522 /// let store = Store::in_memory()?;
523 /// store.queue().enqueue("job-1", "M31").await?;
524 /// store.queue().enqueue("job-1", "M31").await?; // idempotent
525 /// assert_eq!(store.queue().pending_count().await?, 1);
526 /// # Ok(()) }
527 /// ```
528 async fn enqueue(&self, id: &str, query: &str) -> Result<(), QueueError>;
529
530 /// Claim up to `n` pending items for processing (approximately FIFO).
531 ///
532 /// ```
533 /// use simbad_resolver::{PendingState, Queue, Store};
534 ///
535 /// # async fn run() -> Result<(), simbad_resolver::Error> {
536 /// let store = Store::in_memory()?;
537 /// store.queue().enqueue("job-1", "M31").await?;
538 /// let claimed = store.queue().claim_pending(8).await?;
539 /// assert_eq!(claimed.len(), 1);
540 /// assert_eq!(claimed[0].state, PendingState::Pending);
541 /// # Ok(()) }
542 /// ```
543 async fn claim_pending(&self, n: usize) -> Result<Vec<PendingItem>, QueueError>;
544
545 /// Mark an item resolved and bind its target (attempts unchanged).
546 ///
547 /// ```
548 /// use simbad_resolver::{PendingState, Queue, Store};
549 /// use uuid::Uuid;
550 ///
551 /// # async fn run() -> Result<(), simbad_resolver::Error> {
552 /// let store = Store::in_memory()?;
553 /// store.queue().enqueue("job-1", "M31").await?;
554 /// store.queue().mark_resolved("job-1", Uuid::nil()).await?;
555 /// let item = store.queue().get("job-1").await?.expect("still present");
556 /// assert_eq!(item.state, PendingState::Resolved);
557 /// assert_eq!(item.target_id, Some(Uuid::nil()));
558 /// # Ok(()) }
559 /// ```
560 async fn mark_resolved(&self, id: &str, target_id: Uuid) -> Result<(), QueueError>;
561
562 /// Mark an item unresolved (content miss); attempts += 1.
563 ///
564 /// ```
565 /// use simbad_resolver::{PendingState, Queue, Store};
566 ///
567 /// # async fn run() -> Result<(), simbad_resolver::Error> {
568 /// let store = Store::in_memory()?;
569 /// store.queue().enqueue("job-1", "does-not-exist").await?;
570 /// store.queue().mark_unresolved("job-1").await?;
571 /// let item = store.queue().get("job-1").await?.expect("still present");
572 /// assert_eq!(item.state, PendingState::Unresolved);
573 /// assert_eq!(item.attempts, 1);
574 /// # Ok(()) }
575 /// ```
576 async fn mark_unresolved(&self, id: &str) -> Result<(), QueueError>;
577
578 /// Release a claimed item back to pending after a transient failure
579 /// (attempts unchanged).
580 ///
581 /// ```
582 /// use simbad_resolver::{PendingState, Queue, Store};
583 ///
584 /// # async fn run() -> Result<(), simbad_resolver::Error> {
585 /// let store = Store::in_memory()?;
586 /// store.queue().enqueue("job-1", "M31").await?;
587 /// store.queue().claim_pending(8).await?; // simulate a claim
588 /// store.queue().release("job-1").await?; // ... then a transient failure
589 /// let item = store.queue().get("job-1").await?.expect("still present");
590 /// assert_eq!(item.state, PendingState::Pending);
591 /// assert_eq!(item.attempts, 0, "transient failures don't spend the attempt budget");
592 /// # Ok(()) }
593 /// ```
594 async fn release(&self, id: &str) -> Result<(), QueueError>;
595
596 /// Read a single item by id.
597 ///
598 /// ```
599 /// use simbad_resolver::{Queue, Store};
600 ///
601 /// # async fn run() -> Result<(), simbad_resolver::Error> {
602 /// let store = Store::in_memory()?;
603 /// assert!(store.queue().get("job-1").await?.is_none());
604 /// store.queue().enqueue("job-1", "M31").await?;
605 /// assert_eq!(store.queue().get("job-1").await?.unwrap().query, "M31");
606 /// # Ok(()) }
607 /// ```
608 async fn get(&self, id: &str) -> Result<Option<PendingItem>, QueueError>;
609
610 /// Count items still `pending`.
611 ///
612 /// ```
613 /// use simbad_resolver::{Queue, Store};
614 /// use uuid::Uuid;
615 ///
616 /// # async fn run() -> Result<(), simbad_resolver::Error> {
617 /// let store = Store::in_memory()?;
618 /// store.queue().enqueue("job-1", "M31").await?;
619 /// store.queue().enqueue("job-2", "M101").await?;
620 /// store.queue().mark_resolved("job-1", Uuid::nil()).await?;
621 /// assert_eq!(store.queue().pending_count().await?, 1);
622 /// # Ok(()) }
623 /// ```
624 async fn pending_count(&self) -> Result<usize, QueueError>;
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630 use crate::types::AliasKind;
631
632 #[test]
633 fn pending_state_wire_round_trips() {
634 for st in [PendingState::Pending, PendingState::Resolved, PendingState::Unresolved] {
635 assert_eq!(PendingState::from_wire(st.as_wire()), Some(st));
636 }
637 assert_eq!(PendingState::Pending.as_wire(), "pending");
638 assert_eq!(PendingState::Resolved.as_wire(), "resolved");
639 assert_eq!(PendingState::Unresolved.as_wire(), "unresolved");
640 assert_eq!(PendingState::from_wire("bogus"), None);
641 assert_eq!(PendingState::from_wire(""), None);
642 }
643
644 #[test]
645 fn cached_target_to_identity_preserves_the_identity_fields() {
646 let target = CachedTarget {
647 id: Uuid::nil(),
648 simbad_oid: Some(1_575_544),
649 primary_designation: "M 31".to_owned(),
650 common_name: Some("Andromeda Galaxy".to_owned()),
651 object_type: ObjectType::Galaxy,
652 otype_raw: "G".to_owned(),
653 ra_deg: 10.684_708,
654 dec_deg: 41.268_75,
655 v_mag: Some(3.44),
656 source: TargetSource::Resolved,
657 resolved_at: "2026-07-11T00:00:00Z".to_owned(),
658 aliases: vec![ResolvedAlias::new("NGC 224", AliasKind::Designation)],
659 };
660
661 let identity = target.to_identity();
662 assert_eq!(identity.simbad_oid, Some(1_575_544));
663 assert_eq!(identity.primary_designation, "M 31");
664 assert_eq!(identity.common_name.as_deref(), Some("Andromeda Galaxy"));
665 assert_eq!(identity.object_type, ObjectType::Galaxy);
666 assert_eq!(identity.otype_raw, "G");
667 assert_eq!(identity.v_mag, Some(3.44));
668 assert!((identity.ra_deg - 10.684_708).abs() < f64::EPSILON);
669 assert_eq!(identity.source, TargetSource::Resolved);
670 assert_eq!(identity.aliases, target.aliases);
671 }
672}