Skip to main content

codewhale_config/
catalog.rs

1//! Models.dev-backed provider catalog snapshots and a secret-free live cache
2//! (#3385, feeding EPIC #2608 and #3383).
3//!
4//! This module is **network-free** by construction. Callers supply parsed
5//! [`crate::models_dev::ModelsDevCatalog`] JSON (bundled snapshot or live
6//! refresh) and live [`ProviderCatalogDelta`]s; the HTTP `/models` fetch layer
7//! lives above this module. Nothing here performs I/O or reads credentials.
8//!
9//! Layering (lowest precedence first; #4188):
10//!
11//! ```text
12//! bundled Models.dev snapshot       (offline/stale fallback only — not competing truth)
13//!   < live Models.dev / provider `/models` cache
14//!   < user / custom overrides        (custom endpoints, pinned models, explicit facts)
15//! ```
16//!
17//! After #4187, live Models.dev rows are preferred whenever present. The bundled
18//! asset remains so offline startup and failed refreshes still resolve defaults.
19//!
20//! Invariants preserved from #2608 / #3497:
21//! - A catalog row is **not** an executable route. Rows still compile through
22//!   `RouteResolver` into a `ReadyRouteCandidate` before execution.
23//! - `wire_model_id` is kept separate from `canonical_model`; a provider row may
24//!   not expose a canonical `base_model` join, and a prefix never proves
25//!   canonical ownership.
26//! - Unknown / custom / local rows are supported with explicit provenance and a
27//!   `None` canonical model.
28//!
29//! The on-disk cache format intentionally uses plain `String` identity fields
30//! rather than the internal route newtypes, so the persisted shape is decoupled
31//! from internal types and trivially auditable for "no secrets" (see
32//! [`ProviderCatalogCache`] tests).
33
34use std::collections::BTreeMap;
35use std::time::{SystemTime, UNIX_EPOCH};
36
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39
40use crate::models_dev::{ModelsDevCatalog, ModelsDevCost, ModelsDevLimit, ModelsDevModalities};
41use crate::route::{ModelId, ProviderId, ProviderModelOffering, RouteLimits, WireModelId};
42
43/// Provenance of a catalog row. Drives layer precedence and UI provenance.
44#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(tag = "kind", rename_all = "snake_case")]
46pub enum CatalogSource {
47    /// Offline/stale bundled seed (Models.dev-shaped snapshot). Not competing
48    /// truth — live Models.dev rows override this layer (#4188).
49    #[default]
50    Bundled,
51    /// A provider live `/models` row, scoped to a base-URL fingerprint and the
52    /// unix timestamp it was fetched at.
53    Live {
54        base_url_fingerprint: String,
55        fetched_at: u64,
56    },
57    /// A user / custom override (custom endpoint, pinned model, explicit facts).
58    UserOverride,
59}
60
61/// One catalog-layer offering row.
62///
63/// This carries the routing identity (provider + wire id + optional canonical
64/// model + endpoint) plus the offering-owned Models.dev facts CodeWhale wants to
65/// preserve (family, limits, cost, reasoning support/options). It is a superset
66/// of [`ProviderModelOffering`]; use [`CatalogOffering::to_offering`] to project
67/// the minimal routing identity the resolver consumes.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
69pub struct CatalogOffering {
70    /// Provider id serving this offering.
71    pub provider: String,
72    /// Provider-owned wire id sent on the request (verbatim).
73    pub wire_model_id: String,
74    /// Canonical model identity, only when an explicit join exists.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub canonical_model: Option<String>,
77    /// Endpoint key the offering is served on (e.g. `chat`).
78    pub endpoint_key: String,
79    /// Whether this is the provider's default offering.
80    #[serde(default)]
81    pub default_for_provider: bool,
82    /// Model family/series as exposed for this offering (e.g. `glm`, `deepseek`).
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub family: Option<String>,
85    /// Token limits for this offering, when known.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub limit: Option<ModelsDevLimit>,
88    /// Provider-scoped pricing, when known.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub cost: Option<ModelsDevCost>,
91    /// Input/output modalities for this offering, when known. Carried as the
92    /// raw Models.dev shape so a factual `text` vs `multimodal` label can be
93    /// derived without guessing; `None` means the layer did not state it (an
94    /// unknown, not "text-only").
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub modalities: Option<ModelsDevModalities>,
97    /// Whether this offering supports reasoning, when known.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub reasoning: Option<bool>,
100    /// Whether tool calling is supported, when known (#4115).
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub tool_call: Option<bool>,
103    /// Provider-scoped reasoning controls / accepted effort metadata. Kept as
104    /// raw JSON so the same model family served through different gateways can
105    /// expose different effort vocabularies without lossy collapsing.
106    #[serde(default, skip_serializing_if = "Vec::is_empty")]
107    pub reasoning_options: Vec<Value>,
108    /// Where this row came from.
109    pub source: CatalogSource,
110}
111
112impl CatalogOffering {
113    /// The provider id as a route newtype.
114    #[must_use]
115    pub fn provider_id(&self) -> ProviderId {
116        ProviderId::from(self.provider.clone())
117    }
118
119    /// The wire model id as a route newtype.
120    #[must_use]
121    pub fn wire_id(&self) -> WireModelId {
122        WireModelId::from(self.wire_model_id.clone())
123    }
124
125    /// Project the minimal routing identity the resolver consumes.
126    ///
127    /// The catalog deliberately carries richer facts than routing needs; this
128    /// drops most of them so `RouteResolver::from_offerings` stays the single
129    /// seam. The route-facing pricing meter is the exception: it is projected
130    /// here (where the offering's sourced `cost` is in scope) via
131    /// [`crate::pricing::route_pricing_sku`] so a resolved candidate can carry
132    /// honest pricing without the route layer ever seeing raw cost (#3085).
133    #[must_use]
134    pub fn to_offering(&self) -> ProviderModelOffering {
135        ProviderModelOffering {
136            provider: self.provider_id(),
137            canonical_model: self.canonical_model.clone().map(ModelId::from),
138            wire_model_id: self.wire_id(),
139            endpoint_key: self.endpoint_key.clone(),
140            default_for_provider: self.default_for_provider,
141            limits: self
142                .limit
143                .as_ref()
144                .map(RouteLimits::from)
145                .unwrap_or_default(),
146            pricing: crate::pricing::route_pricing_sku(self),
147        }
148    }
149
150    /// Stable identity key for de-duplication and layer merging.
151    fn merge_key(&self) -> (String, String) {
152        (self.provider.clone(), self.wire_model_id.clone())
153    }
154}
155
156/// Committed offline/stale Models.dev-shaped catalog snapshot (#3385 / #4188).
157///
158/// This is **not** a competing curated source of truth. Preferred metadata comes
159/// from the live Models.dev catalog (#4187). The bundled asset is a compact
160/// network-free seed of verified in-repo defaults (context/output from
161/// `crates/tui/src/models.rs`, USD pricing from `crates/tui/src/pricing.rs`) so
162/// [`crate::route::RouteResolver::new`] and pickers still work offline or after
163/// a failed refresh. See the asset's `_meta.role` / `_meta.source` and the
164/// honesty rule on omitted pricing (`UnknownOrStale`, never a fabricated zero).
165pub const BUNDLED_MODELS_DEV_JSON: &str = include_str!("../assets/models_dev.bundled.json");
166
167/// Parse the committed bundled Models.dev snapshot.
168///
169/// # Panics
170/// Panics only if the committed asset is not valid Models.dev JSON. The
171/// `tests::bundled_asset_parses` guard makes that a build-time failure, so this
172/// never panics in shipped builds.
173#[must_use]
174pub fn bundled_models_dev_catalog() -> ModelsDevCatalog {
175    ModelsDevCatalog::parse_json(BUNDLED_MODELS_DEV_JSON)
176        .expect("committed bundled Models.dev asset must be valid JSON")
177}
178
179/// Bundled-layer [`CatalogOffering`] rows from the offline snapshot (#4188).
180///
181/// Lowest-precedence catalog layer: every text-chat row from
182/// [`BUNDLED_MODELS_DEV_JSON`], tagged [`CatalogSource::Bundled`]. Live Models.dev
183/// rows override these on `(provider, wire_model_id)` when available.
184#[must_use]
185pub fn bundled_catalog_offerings() -> Vec<CatalogOffering> {
186    bundled_offerings_from_models_dev(&bundled_models_dev_catalog())
187}
188
189/// Hydrate bundled [`CatalogOffering`] rows from a parsed Models.dev catalog.
190///
191/// Only text-chat offerings are emitted (TTS/audio-only rows stay in the parsed
192/// catalog but are excluded from route candidates, matching
193/// [`ModelsDevCatalog::provider_offerings`]). Each row is tagged
194/// [`CatalogSource::Bundled`]. No canonical model is inferred from a prefix; the
195/// canonical link is set only from an explicit `base_model`.
196///
197/// Provider ids are kept verbatim from the Models.dev payload (the committed
198/// bundled asset already uses CodeWhale ids). Live refresh normalizes aliases
199/// via [`live_offerings_from_models_dev`].
200#[must_use]
201pub fn bundled_offerings_from_models_dev(catalog: &ModelsDevCatalog) -> Vec<CatalogOffering> {
202    offerings_from_models_dev(catalog, CatalogSource::Bundled, false)
203}
204
205/// Hydrate live [`CatalogOffering`] rows from a fetched Models.dev catalog (#4187).
206///
207/// Same text-chat filter as [`bundled_offerings_from_models_dev`], but each row is
208/// tagged [`CatalogSource::Live`] with the Models.dev URL fingerprint and fetch
209/// timestamp. Provider keys are normalized onto CodeWhale [`crate::ProviderKind`]
210/// ids when an alias match exists (`moonshotai` → `moonshot`, `togetherai` →
211/// `together`, `zhipuai` → `zai`, …); unknown Models.dev providers keep their
212/// upstream id so they stay discoverable without becoming executable routes.
213#[must_use]
214pub fn live_offerings_from_models_dev(
215    catalog: &ModelsDevCatalog,
216    base_url_fingerprint: &str,
217    fetched_at: u64,
218) -> Vec<CatalogOffering> {
219    offerings_from_models_dev(
220        catalog,
221        CatalogSource::Live {
222            base_url_fingerprint: base_url_fingerprint.to_string(),
223            fetched_at,
224        },
225        true,
226    )
227}
228
229fn offerings_from_models_dev(
230    catalog: &ModelsDevCatalog,
231    source: CatalogSource,
232    normalize_provider_ids: bool,
233) -> Vec<CatalogOffering> {
234    let mut out = Vec::new();
235    for (provider_key, provider) in &catalog.providers {
236        let raw_id = if provider.id.trim().is_empty() {
237            provider_key.trim()
238        } else {
239            provider.id.trim()
240        };
241        if raw_id.is_empty() {
242            continue;
243        }
244        let provider_id = if normalize_provider_ids {
245            // Normalize Models.dev provider ids onto CodeWhale kinds when known
246            // (#4186). Unknown upstream ids are kept verbatim for catalog browsing.
247            crate::ProviderKind::parse(raw_id)
248                .map(|kind| kind.as_str().to_string())
249                .unwrap_or_else(|| raw_id.to_string())
250        } else {
251            raw_id.to_string()
252        };
253        for model in provider.models.values() {
254            if !model.supports_text_chat() {
255                continue;
256            }
257            out.push(CatalogOffering {
258                provider: provider_id.clone(),
259                wire_model_id: model.id.clone(),
260                canonical_model: model.base_model.clone(),
261                endpoint_key: "chat".to_string(),
262                default_for_provider: model.default_for_provider,
263                family: model.family.clone(),
264                limit: model.limit.clone(),
265                cost: model.cost.clone(),
266                modalities: model.modalities.clone(),
267                reasoning: model.reasoning,
268                tool_call: model.tool_call,
269                reasoning_options: model.reasoning_options.clone(),
270                source: source.clone(),
271            });
272        }
273    }
274    out
275}
276
277/// A provider's live `/models` refresh result, scoped to a base-URL fingerprint.
278///
279/// Returned as a delta rather than mutating any global model state directly, per
280/// the #3385 architecture contract.
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282pub struct ProviderCatalogDelta {
283    /// Provider this delta belongs to.
284    pub provider: String,
285    /// Fingerprint of the base URL the rows were fetched from.
286    pub base_url_fingerprint: String,
287    /// Unix seconds the rows were fetched at.
288    pub fetched_at: u64,
289    /// Live offering rows. Sources are normalized to `Live` on ingest.
290    pub offerings: Vec<CatalogOffering>,
291}
292
293/// Why a provider live catalog refresh did not produce usable rows.
294///
295/// Every variant must leave previously cached / bundled / configured rows
296/// available; a refresh failure is never fatal to model selection.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "snake_case")]
299pub enum CatalogRefreshError {
300    /// 401 — auth missing or invalid.
301    Unauthorized,
302    /// 403 — auth present but not permitted.
303    Forbidden,
304    /// 404 — provider does not expose `/models` at this base URL.
305    NotFound,
306    /// 429 — rate limited.
307    RateLimited,
308    /// Response was not parseable as a model listing.
309    InvalidResponse,
310    /// Provider returned an empty model list.
311    EmptyList,
312    /// Transport / network failure.
313    Network,
314}
315
316/// Freshness / health of a provider's cached live catalog.
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318#[serde(tag = "state", rename_all = "snake_case")]
319pub enum CatalogStatus {
320    /// Cached rows are within their TTL.
321    Fresh,
322    /// Cached rows exist but are past their TTL.
323    Stale { age_secs: u64 },
324    /// The last refresh failed; any rows present are from an earlier success.
325    Failed { reason: CatalogRefreshError },
326    /// No refresh has been attempted for this provider + base URL.
327    Unknown,
328}
329
330/// A secret-free cached provider catalog for one provider + base-URL fingerprint.
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332pub struct CachedProviderCatalog {
333    /// Provider id.
334    pub provider: String,
335    /// Base-URL fingerprint the rows were fetched from.
336    pub base_url_fingerprint: String,
337    /// Unix seconds of the last successful fetch (unchanged on failure).
338    pub fetched_at: u64,
339    /// Time-to-live, in seconds, after which rows are considered stale.
340    pub ttl_secs: u64,
341    /// Cached live offering rows (possibly empty after a failure with no prior).
342    pub offerings: Vec<CatalogOffering>,
343    /// Last known status of this entry.
344    pub status: CatalogStatus,
345}
346
347impl CachedProviderCatalog {
348    /// Age in seconds relative to `now_unix`, saturating at zero for clock skew.
349    #[must_use]
350    pub fn age_secs(&self, now_unix: u64) -> u64 {
351        now_unix.saturating_sub(self.fetched_at)
352    }
353
354    /// Whether the cached rows are past their TTL at `now_unix`.
355    ///
356    /// A `ttl_secs` of zero means "always stale" (never serve as fresh).
357    #[must_use]
358    pub fn is_stale(&self, now_unix: u64) -> bool {
359        self.age_secs(now_unix) >= self.ttl_secs
360    }
361
362    /// Whether this entry may contribute live offerings at `now_unix`.
363    ///
364    /// An entry is fresh only when it is within its TTL **and** its last
365    /// recorded refresh succeeded. A `Failed` entry is never fresh even inside
366    /// its TTL window — its rows survive a failed refresh for explicit fallback
367    /// display via [`ProviderCatalogCache::get`], but they are not served as
368    /// current live data.
369    #[must_use]
370    pub fn is_fresh(&self, now_unix: u64) -> bool {
371        !self.is_stale(now_unix) && !matches!(self.status, CatalogStatus::Failed { .. })
372    }
373}
374
375/// A secret-free store of cached provider catalogs, keyed by provider + base-URL
376/// fingerprint.
377///
378/// Scoping rule (#3385): the SAME provider on DIFFERENT base URLs must not share
379/// rows, and DIFFERENT providers on the same base URL must not share rows.
380#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
381pub struct ProviderCatalogCache {
382    /// Entries keyed by [`ProviderCatalogCache::cache_key`].
383    #[serde(default)]
384    pub entries: BTreeMap<String, CachedProviderCatalog>,
385}
386
387impl ProviderCatalogCache {
388    /// Construct an empty cache.
389    #[must_use]
390    pub fn new() -> Self {
391        Self::default()
392    }
393
394    /// Compute the composite cache key for a provider + base-URL fingerprint.
395    #[must_use]
396    pub fn cache_key(provider: &str, base_url_fingerprint: &str) -> String {
397        // Unit separator avoids ambiguity between provider and fingerprint.
398        format!("{}\u{1f}{}", provider.trim(), base_url_fingerprint.trim())
399    }
400
401    /// Look up a cached entry by provider + base-URL fingerprint.
402    #[must_use]
403    pub fn get(
404        &self,
405        provider: &str,
406        base_url_fingerprint: &str,
407    ) -> Option<&CachedProviderCatalog> {
408        self.entries
409            .get(&Self::cache_key(provider, base_url_fingerprint))
410    }
411
412    /// Record a successful refresh, replacing any prior entry for this scope.
413    ///
414    /// Offering sources are normalized to [`CatalogSource::Live`] with the
415    /// delta's fingerprint and `fetched_at`, so cached rows always carry honest
416    /// provenance regardless of how the delta was assembled.
417    pub fn record_success(&mut self, delta: ProviderCatalogDelta, ttl_secs: u64) {
418        let ProviderCatalogDelta {
419            provider,
420            base_url_fingerprint,
421            fetched_at,
422            offerings,
423        } = delta;
424        let offerings = offerings
425            .into_iter()
426            .map(|mut row| {
427                row.source = CatalogSource::Live {
428                    base_url_fingerprint: base_url_fingerprint.clone(),
429                    fetched_at,
430                };
431                row
432            })
433            .collect();
434        let key = Self::cache_key(&provider, &base_url_fingerprint);
435        self.entries.insert(
436            key,
437            CachedProviderCatalog {
438                provider,
439                base_url_fingerprint,
440                fetched_at,
441                ttl_secs,
442                offerings,
443                status: CatalogStatus::Fresh,
444            },
445        );
446    }
447
448    /// Record a refresh failure.
449    ///
450    /// Previously cached rows for this scope are preserved (so the UI can still
451    /// offer them with a visible "stale/failed" status); only the status is
452    /// updated. When no prior entry exists, an empty `Failed` entry is created so
453    /// the failure is observable.
454    pub fn record_failure(
455        &mut self,
456        provider: &str,
457        base_url_fingerprint: &str,
458        reason: CatalogRefreshError,
459    ) {
460        let key = Self::cache_key(provider, base_url_fingerprint);
461        match self.entries.get_mut(&key) {
462            Some(entry) => entry.status = CatalogStatus::Failed { reason },
463            None => {
464                self.entries.insert(
465                    key,
466                    CachedProviderCatalog {
467                        provider: provider.trim().to_string(),
468                        base_url_fingerprint: base_url_fingerprint.trim().to_string(),
469                        fetched_at: 0,
470                        ttl_secs: 0,
471                        offerings: Vec::new(),
472                        status: CatalogStatus::Failed { reason },
473                    },
474                );
475            }
476        }
477    }
478
479    /// The resolved status of an entry at `now_unix`.
480    ///
481    /// A `Fresh`-recorded entry that has since aged past its TTL reports
482    /// `Stale`; `Failed`/`Unknown` are returned as stored.
483    #[must_use]
484    pub fn status(
485        &self,
486        provider: &str,
487        base_url_fingerprint: &str,
488        now_unix: u64,
489    ) -> CatalogStatus {
490        match self.get(provider, base_url_fingerprint) {
491            None => CatalogStatus::Unknown,
492            Some(entry) => match &entry.status {
493                CatalogStatus::Failed { reason } => CatalogStatus::Failed { reason: *reason },
494                CatalogStatus::Unknown => CatalogStatus::Unknown,
495                CatalogStatus::Fresh | CatalogStatus::Stale { .. } => {
496                    if entry.is_stale(now_unix) {
497                        CatalogStatus::Stale {
498                            age_secs: entry.age_secs(now_unix),
499                        }
500                    } else {
501                        CatalogStatus::Fresh
502                    }
503                }
504            },
505        }
506    }
507
508    /// Fresh (within-TTL) live offerings for one provider + base URL at
509    /// `now_unix`. Stale or failed entries contribute nothing here; callers fall
510    /// back to bundled/configured rows and surface the status separately.
511    #[must_use]
512    pub fn fresh_offerings(
513        &self,
514        provider: &str,
515        base_url_fingerprint: &str,
516        now_unix: u64,
517    ) -> Vec<CatalogOffering> {
518        match self.get(provider, base_url_fingerprint) {
519            Some(entry) if entry.is_fresh(now_unix) => entry.offerings.clone(),
520            _ => Vec::new(),
521        }
522    }
523
524    /// All fresh live offerings across every cached provider + base URL.
525    #[must_use]
526    pub fn all_fresh_offerings(&self, now_unix: u64) -> Vec<CatalogOffering> {
527        self.entries
528            .values()
529            .filter(|entry| entry.is_fresh(now_unix))
530            .flat_map(|entry| entry.offerings.clone())
531            .collect()
532    }
533
534    /// Live offerings that pickers may still show: fresh rows plus stale / prior
535    /// rows that survived a failed refresh (#4139).
536    ///
537    /// Unlike [`Self::all_fresh_offerings`], this keeps past-TTL and
538    /// `Failed`-status entries as long as they still hold offering rows. Empty
539    /// entries contribute nothing; callers fall back to the bundled snapshot.
540    /// `now_unix` is accepted for API symmetry with the fresh helper (age chips
541    /// live above this layer).
542    #[must_use]
543    pub fn all_visible_offerings(&self, _now_unix: u64) -> Vec<CatalogOffering> {
544        self.entries
545            .values()
546            .filter(|entry| !entry.offerings.is_empty())
547            .flat_map(|entry| entry.offerings.clone())
548            .collect()
549    }
550}
551
552/// A compiled, layer-merged catalog snapshot.
553#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
554pub struct CatalogSnapshot {
555    /// Merged offerings, de-duplicated by (provider, wire id), in stable order.
556    pub offerings: Vec<CatalogOffering>,
557}
558
559impl CatalogSnapshot {
560    /// Project routing offerings for `RouteResolver::from_offerings`.
561    #[must_use]
562    pub fn to_offerings(&self) -> Vec<ProviderModelOffering> {
563        self.offerings
564            .iter()
565            .map(CatalogOffering::to_offering)
566            .collect()
567    }
568
569    /// All offerings for one provider id.
570    #[must_use]
571    pub fn offerings_for_provider(&self, provider: &str) -> Vec<&CatalogOffering> {
572        self.offerings
573            .iter()
574            .filter(|row| row.provider == provider)
575            .collect()
576    }
577}
578
579/// Builds a [`CatalogSnapshot`] by merging layers in precedence order:
580/// bundled < live < user overrides. Later layers override earlier rows that
581/// share a (provider, wire id) identity.
582#[derive(Debug, Clone, Default)]
583pub struct CatalogCompiler {
584    bundled: Vec<CatalogOffering>,
585    live: Vec<CatalogOffering>,
586    overrides: Vec<CatalogOffering>,
587}
588
589impl CatalogCompiler {
590    /// Start an empty compiler.
591    #[must_use]
592    pub fn new() -> Self {
593        Self::default()
594    }
595
596    /// Add bundled (lowest-precedence) rows.
597    #[must_use]
598    pub fn with_bundled(mut self, rows: Vec<CatalogOffering>) -> Self {
599        self.bundled.extend(rows);
600        self
601    }
602
603    /// Seed bundled rows from a parsed Models.dev catalog.
604    #[must_use]
605    pub fn with_models_dev(mut self, catalog: &ModelsDevCatalog) -> Self {
606        self.bundled
607            .extend(bundled_offerings_from_models_dev(catalog));
608        self
609    }
610
611    /// Add live (middle-precedence) rows.
612    #[must_use]
613    pub fn with_live(mut self, rows: Vec<CatalogOffering>) -> Self {
614        self.live.extend(rows);
615        self
616    }
617
618    /// Add user/custom override (highest-precedence) rows.
619    #[must_use]
620    pub fn with_overrides(mut self, rows: Vec<CatalogOffering>) -> Self {
621        self.overrides.extend(rows);
622        self
623    }
624
625    /// Merge all layers into a deterministic snapshot.
626    #[must_use]
627    pub fn compile(self) -> CatalogSnapshot {
628        let mut merged: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new();
629        for row in self
630            .bundled
631            .into_iter()
632            .chain(self.live)
633            .chain(self.overrides)
634        {
635            merged.insert(row.merge_key(), row);
636        }
637        CatalogSnapshot {
638            offerings: merged.into_values().collect(),
639        }
640    }
641}
642
643/// Normalize a base URL and fingerprint it for cache scoping.
644///
645/// Normalization folds case in the scheme/host, trims trailing slashes, and
646/// drops a default-port suffix, so cosmetically different spellings of the same
647/// endpoint share a cache scope while genuinely different endpoints do not. The
648/// fingerprint is a dependency-free FNV-1a hex digest; it is deterministic
649/// within and across runs but is not a cryptographic hash (it identifies a
650/// cache bucket, nothing security-sensitive).
651#[must_use]
652pub fn base_url_fingerprint(base_url: &str) -> String {
653    let normalized = normalize_base_url(base_url);
654    fnv1a_hex(normalized.as_bytes())
655}
656
657fn normalize_base_url(base_url: &str) -> String {
658    let trimmed = base_url.trim().trim_end_matches('/');
659    // Lowercase only the scheme://host authority; leave the path case-sensitive.
660    if let Some(idx) = trimmed.find("://") {
661        let (scheme, rest) = trimmed.split_at(idx);
662        let scheme = scheme.to_ascii_lowercase();
663        let rest = &rest[3..];
664        let (authority, path) = match rest.find('/') {
665            Some(p) => (&rest[..p], &rest[p..]),
666            None => (rest, ""),
667        };
668        let authority = authority.to_ascii_lowercase();
669        // Strip only the scheme's own default port, so a non-default pairing
670        // such as `http://host:443` stays distinct from `http://host`.
671        let default_port = match scheme.as_str() {
672            "https" => Some(":443"),
673            "http" => Some(":80"),
674            _ => None,
675        };
676        let authority = default_port
677            .and_then(|port| authority.strip_suffix(port))
678            .unwrap_or(&authority);
679        format!("{scheme}://{authority}{path}")
680    } else {
681        trimmed.to_ascii_lowercase()
682    }
683}
684
685fn fnv1a_hex(bytes: &[u8]) -> String {
686    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
687    const PRIME: u64 = 0x0000_0100_0000_01b3;
688    let mut hash = OFFSET;
689    for &b in bytes {
690        hash ^= u64::from(b);
691        hash = hash.wrapping_mul(PRIME);
692    }
693    format!("{hash:016x}")
694}
695
696/// Current unix time in seconds, for callers assembling deltas / cache entries.
697///
698/// Pure cache logic takes `now_unix` explicitly so it stays deterministic in
699/// tests; this helper is the one place that reads the wall clock.
700#[must_use]
701pub fn now_unix() -> u64 {
702    SystemTime::now()
703        .duration_since(UNIX_EPOCH)
704        .map(|d| d.as_secs())
705        .unwrap_or(0)
706}
707
708#[cfg(test)]
709mod tests;