Skip to main content

adk_site/migrate/
inventory.rs

1//! The inventory a source produces (spec 3.5 §7.8 "Sources", §7.18 stage 2).
2
3use std::collections::BTreeMap;
4
5use awp_types::{ContentKind, Digest};
6use bytes::Bytes;
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::gate::FactStatus;
12
13/// Which source produced an inventory.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16#[non_exhaustive]
17pub enum SourceKind {
18    /// The public `wp-json/wp/v2` collections.
19    WordPressRest,
20    /// A WordPress export file.
21    Wxr,
22    /// A crawl of any site.
23    Crawl,
24    /// Business profiles, listings, reviews and social pages.
25    Presence,
26    /// A database dump and uploads replayed in an isolated container.
27    IsolatedReplay,
28}
29
30/// Everything a source found: URLs, items, media, taxonomies, menus, dynamic features and,
31/// for a presence, facts and reviews (spec 3.5 §7.8).
32///
33/// # Example
34///
35/// ```rust
36/// use adk_site::migrate::{SiteInventory, SourceKind};
37///
38/// let inventory = SiteInventory::new(SourceKind::Crawl, chrono::Utc::now());
39/// assert!(inventory.items.is_empty());
40/// ```
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct SiteInventory {
44    /// The source.
45    pub source: SourceKind,
46    /// The legacy site's public origin, such as `https://example.com`.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub origin: Option<String>,
49    /// The site's name.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub site_name: Option<String>,
52    /// The site's description or tagline.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub description: Option<String>,
55    /// The site's language, when it declares one.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub language: Option<String>,
58    /// When the inventory was taken.
59    pub taken_at: DateTime<Utc>,
60    /// Every URL seen, with how it answered.
61    #[serde(default)]
62    pub urls: Vec<InventoryUrl>,
63    /// Posts, pages, products and other items.
64    #[serde(default)]
65    pub items: Vec<InventoryItem>,
66    /// Uploads and other media.
67    #[serde(default)]
68    pub media: Vec<InventoryMedia>,
69    /// Categories, tags and other taxonomies.
70    #[serde(default)]
71    pub taxonomies: Vec<Taxonomy>,
72    /// Navigation menus.
73    #[serde(default)]
74    pub menus: Vec<Menu>,
75    /// Dynamic features found: forms, search, comments, shop, bookings, logins.
76    #[serde(default)]
77    pub features: Vec<DetectedFeature>,
78    /// Facts found, each with its source; every one `Assumed` until the owner confirms it.
79    #[serde(default)]
80    pub facts: Vec<Fact>,
81    /// Reviews found on public platforms.
82    #[serde(default)]
83    pub reviews: Vec<ReviewQuote>,
84    /// What the source did not read, and why.
85    #[serde(default)]
86    pub notes: Vec<String>,
87}
88
89impl SiteInventory {
90    /// An empty inventory.
91    pub fn new(source: SourceKind, taken_at: DateTime<Utc>) -> Self {
92        Self {
93            source,
94            origin: None,
95            site_name: None,
96            description: None,
97            language: None,
98            taken_at,
99            urls: Vec::new(),
100            items: Vec::new(),
101            media: Vec::new(),
102            taxonomies: Vec::new(),
103            menus: Vec::new(),
104            features: Vec::new(),
105            facts: Vec::new(),
106            reviews: Vec::new(),
107            notes: Vec::new(),
108        }
109    }
110
111    /// The item with `key`.
112    pub fn item(&self, key: &str) -> Option<&InventoryItem> {
113        self.items.iter().find(|item| item.key == key)
114    }
115
116    /// The URL record for `path`.
117    pub fn url(&self, path: &str) -> Option<&InventoryUrl> {
118        self.urls.iter().find(|url| url.path == path)
119    }
120
121    /// Records a feature, merging evidence into an existing one of the same kind.
122    pub fn add_feature(&mut self, feature: DetectedFeature) {
123        match self.features.iter_mut().find(|f| f.kind == feature.kind) {
124            Some(existing) => {
125                for evidence in feature.evidence {
126                    if !existing.evidence.contains(&evidence) {
127                        existing.evidence.push(evidence);
128                    }
129                }
130                for field in feature.fields {
131                    if !existing.fields.iter().any(|f| f.name == field.name) {
132                        existing.fields.push(field);
133                    }
134                }
135            }
136            None => self.features.push(feature),
137        }
138    }
139
140    /// The facts found, as a claim check: each one `Assumed`, so a page that cites one fails
141    /// the launch gate until the owner confirms it (A-I18, S2).
142    pub fn fact_table(&self) -> crate::gate::FactTable {
143        crate::gate::FactTable::new(
144            self.facts.iter().map(|f| (awp_types::FactRef(f.id.clone()), f.status)),
145        )
146    }
147
148    /// Whether a feature of `kind` was found.
149    pub fn has_feature(&self, kind: FeatureKind) -> bool {
150        self.features.iter().any(|f| f.kind == kind)
151    }
152
153    /// The `n` most important HTML pages answering 200: the home page first, then by inbound
154    /// internal links, then by path (spec 3.5 §7.8.1 "top N pages").
155    pub fn top_pages(&self, n: usize) -> Vec<&InventoryUrl> {
156        let mut pages: Vec<&InventoryUrl> =
157            self.urls.iter().filter(|u| u.status == 200 && u.page.is_some()).collect();
158        pages.sort_by(|a, b| {
159            (b.path == "/")
160                .cmp(&(a.path == "/"))
161                .then(b.inbound_links.cmp(&a.inbound_links))
162                .then(a.path.cmp(&b.path))
163        });
164        pages.truncate(n);
165        pages
166    }
167}
168
169/// One URL of the legacy site and how it answered.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "camelCase")]
172pub struct InventoryUrl {
173    /// The absolute public URL.
174    pub url: String,
175    /// Its path and query, such as `/about/`.
176    pub path: String,
177    /// The HTTP status, or 200 for a URL read from an export.
178    pub status: u16,
179    /// Where a redirect points, as a path on the same site or an absolute URL.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub redirect_to: Option<String>,
182    /// The response's media type.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub content_type: Option<String>,
185    /// The digest of the response body.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub sha256: Option<Digest>,
188    /// The item this URL shows.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub item: Option<String>,
191    /// What an HTML page says about itself.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub page: Option<PageMeta>,
194    /// Internal links pointing here.
195    #[serde(default)]
196    pub inbound_links: u32,
197    /// The body as read, for the detectors; never serialised.
198    #[serde(skip)]
199    pub body: Option<Bytes>,
200}
201
202/// The metadata and main text of an HTML page (spec 3.5 §7.8.1 "metadata preserved",
203/// "main-text similarity").
204#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "camelCase")]
206pub struct PageMeta {
207    /// `<title>`.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub title: Option<String>,
210    /// `<meta name="description">`.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub description: Option<String>,
213    /// `<link rel="canonical">`, as a path when it is on the same site.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub canonical: Option<String>,
216    /// `<html lang>`.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub language: Option<String>,
219    /// Open Graph properties, such as `og:title`.
220    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
221    pub open_graph: BTreeMap<String, String>,
222    /// The visible text of the main content, whitespace collapsed.
223    #[serde(default)]
224    pub main_text: String,
225}
226
227/// Where an item stands on the legacy site.
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
229#[serde(rename_all = "snake_case")]
230#[non_exhaustive]
231pub enum ItemStatus {
232    /// Public.
233    Published,
234    /// A draft, read with the owner's credential.
235    Draft,
236    /// Waiting for review.
237    Pending,
238    /// Scheduled for later.
239    Scheduled,
240    /// Visible to logged-in users only.
241    Private,
242}
243
244/// A post, page, product or other item of the legacy site.
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(rename_all = "camelCase")]
247pub struct InventoryItem {
248    /// A key stable within the source, such as `wp:post:42`.
249    pub key: String,
250    /// The content kind it becomes.
251    pub kind: ContentKind,
252    /// Its slug.
253    pub slug: String,
254    /// Its public URL, when it has one.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub url: Option<String>,
257    /// Its URL path, which the migrated item keeps.
258    pub path: String,
259    /// Its title.
260    pub title: String,
261    /// Its body as the legacy site stores or renders it: HTML, untrusted.
262    #[serde(default)]
263    pub html: String,
264    /// Its excerpt, as HTML.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub excerpt: Option<String>,
267    /// Where it stands.
268    pub status: ItemStatus,
269    /// When it was published.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub published_at: Option<DateTime<Utc>>,
272    /// When it was last changed.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub modified_at: Option<DateTime<Utc>>,
275    /// Its language, when the source knows it.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub language: Option<String>,
278    /// Category names.
279    #[serde(default, skip_serializing_if = "Vec::is_empty")]
280    pub categories: Vec<String>,
281    /// Tag names.
282    #[serde(default, skip_serializing_if = "Vec::is_empty")]
283    pub tags: Vec<String>,
284    /// Structured fields, such as `price`, `currency` and `sku` for a product.
285    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
286    pub fields: BTreeMap<String, Value>,
287    /// URLs of its media.
288    #[serde(default, skip_serializing_if = "Vec::is_empty")]
289    pub media: Vec<String>,
290    /// Its author's display name.
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub author: Option<String>,
293}
294
295/// An upload or other media file.
296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
297#[serde(rename_all = "camelCase")]
298pub struct InventoryMedia {
299    /// Its public URL.
300    pub url: String,
301    /// Its path on the legacy site, such as `/wp-content/uploads/2026/10/a.jpg`.
302    pub path: String,
303    /// The media type the legacy site declared.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub declared_type: Option<String>,
306    /// Its alt text.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub alt: Option<String>,
309    /// The digest of its bytes, when they were read.
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub sha256: Option<Digest>,
312    /// Its size in bytes, when it was read.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub size: Option<u64>,
315    /// Its bytes, when the source read them; never serialised.
316    #[serde(skip)]
317    pub bytes: Option<Bytes>,
318}
319
320impl InventoryMedia {
321    /// A media record for `url` at `path` with nothing read yet.
322    pub fn new(url: impl Into<String>, path: impl Into<String>) -> Self {
323        Self {
324            url: url.into(),
325            path: path.into(),
326            declared_type: None,
327            alt: None,
328            sha256: None,
329            size: None,
330            bytes: None,
331        }
332    }
333
334    /// Attaches the bytes read, with their digest and size.
335    #[must_use]
336    pub fn with_bytes(mut self, bytes: Bytes) -> Self {
337        self.sha256 = Some(crate::release::file_digest(&bytes));
338        self.size = Some(bytes.len() as u64);
339        self.bytes = Some(bytes);
340        self
341    }
342}
343
344/// A taxonomy, such as categories or tags.
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase")]
347pub struct Taxonomy {
348    /// Its name, such as `category` or `post_tag`.
349    pub name: String,
350    /// Its terms.
351    pub terms: Vec<Term>,
352}
353
354/// One term of a taxonomy.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356#[serde(rename_all = "camelCase")]
357pub struct Term {
358    /// Its slug.
359    pub slug: String,
360    /// Its name.
361    pub name: String,
362    /// Its parent's slug.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub parent: Option<String>,
365    /// Its archive URL path.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub path: Option<String>,
368}
369
370/// A navigation menu.
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372#[serde(rename_all = "camelCase")]
373pub struct Menu {
374    /// Its name.
375    pub name: String,
376    /// Its entries, in order.
377    pub entries: Vec<MenuEntry>,
378}
379
380/// One menu entry.
381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
382#[serde(rename_all = "camelCase")]
383pub struct MenuEntry {
384    /// Its label.
385    pub title: String,
386    /// Where it points: a path on the site or an absolute URL.
387    pub target: String,
388    /// Its parent entry's position in `entries`.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub parent: Option<usize>,
391}
392
393/// A dynamic feature the static site replaces (spec 3.5 §7.8 "Feature mapping").
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
395#[serde(rename_all = "snake_case")]
396#[non_exhaustive]
397pub enum FeatureKind {
398    /// A contact form.
399    ContactForm,
400    /// Site search.
401    Search,
402    /// Comments.
403    Comments,
404    /// A shop: products, cart, checkout.
405    Shop,
406    /// Bookings or appointments.
407    Bookings,
408    /// A login form.
409    Login,
410    /// A member area behind a login.
411    MemberArea,
412    /// A newsletter sign-up.
413    Newsletter,
414}
415
416/// Where a feature was seen.
417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
418#[serde(rename_all = "camelCase")]
419pub struct FeatureEvidence {
420    /// The page or document.
421    pub url: String,
422    /// What was seen, such as `form action=/wp-comments-post.php`.
423    pub detail: String,
424}
425
426/// A field of a form the feature uses.
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428#[serde(rename_all = "camelCase")]
429pub struct FormField {
430    /// The field's name.
431    pub name: String,
432    /// Its input type, such as `email` or `textarea`.
433    pub input_type: String,
434    /// Whether it is required.
435    #[serde(default)]
436    pub required: bool,
437}
438
439/// A dynamic feature found on the legacy site.
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441#[serde(rename_all = "camelCase")]
442pub struct DetectedFeature {
443    /// What it is.
444    pub kind: FeatureKind,
445    /// Where it was seen.
446    pub evidence: Vec<FeatureEvidence>,
447    /// The fields of its form, when it has one.
448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
449    pub fields: Vec<FormField>,
450}
451
452/// Where a fact was found.
453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
454#[serde(rename_all = "camelCase")]
455pub struct FactSource {
456    /// The page or document.
457    pub url: String,
458    /// When it was read.
459    pub retrieved_at: DateTime<Utc>,
460    /// Where on the page: a JSON-LD property, a meta tag.
461    pub locator: String,
462}
463
464/// A fact found during discovery: `Assumed` until the owner confirms it, so it never appears
465/// as a published claim (spec 3.5 §7.18 stage 2, A-I18, S2).
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(rename_all = "camelCase")]
468pub struct Fact {
469    /// A stable id, the [`FactRef`](awp_types::FactRef) content items cite.
470    pub id: String,
471    /// What it is about, such as `telephone` or `openingHours`.
472    pub key: String,
473    /// The value found.
474    pub value: String,
475    /// Where it was found.
476    pub source: FactSource,
477    /// Its standing; sources only ever produce `Assumed`.
478    pub status: FactStatus,
479}
480
481/// A review found on a public platform (spec 3.5 S2).
482///
483/// A quote appears on a page only with the reviewer's public attribution and the owner's
484/// approval: [`usable`](Self::usable).
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486#[serde(rename_all = "camelCase")]
487pub struct ReviewQuote {
488    /// The platform's page.
489    pub source: FactSource,
490    /// The reviewer's public display name, when the platform shows one.
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub author: Option<String>,
493    /// The rating, one to five.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub rating: Option<u8>,
496    /// The review's text.
497    pub text: String,
498    /// The owner's decision that approved quoting it.
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub approved_by: Option<String>,
501}
502
503impl ReviewQuote {
504    /// Whether the quote may appear on a page: it has a public attribution and the owner
505    /// approved it.
506    pub fn usable(&self) -> bool {
507        self.author.as_deref().is_some_and(|a| !a.trim().is_empty()) && self.approved_by.is_some()
508    }
509}
510
511impl From<&ReviewQuote> for crate::gate::QuotableReview {
512    /// The review as the launch gate polices quotes of it (spec 3.5 S2).
513    fn from(review: &ReviewQuote) -> Self {
514        Self {
515            text: review.text.clone(),
516            author: review.author.clone(),
517            approved_by: review.approved_by.clone(),
518            source: Some(review.source.url.clone()),
519        }
520    }
521}