Skip to main content

adk_site/feed/
mod.rs

1//! Model-free feed updates (spec 3.5 §7.8.2 "Imports and feeds", §7.8.3 "Model-free updates",
2//! "Bounds on automated feeds", A-I24, A-I27).
3//!
4//! A [`ContentSource`] delivers records — supplier and point-of-sale feeds, exports, wire
5//! feeds. A [`FeedMapping`] turns each record into item fields through declared types, units
6//! and bounds; nothing in this module calls a model. [`FeedMapping::changes`] compares the
7//! mapped values with the items the site holds and sorts each changed field into its lane:
8//! live values go to the edge's [`LiveStore`](crate::live::LiveStore), released values become
9//! item versions for the batcher. [`bounds::check`] then decides whether the delivery may
10//! proceed at all: a delivery that breaks its [`FeedBounds`](awp_types::FeedBounds) is held
11//! whole (A-I27).
12//!
13//! | Source | Delivers |
14//! |--------|----------|
15//! | [`InMemorySource`] | Records pushed by the caller, such as a webhook's deliveries, drained by each pull |
16//! | [`CsvFileSource`] | Every row of a CSV export, read again at each pull |
17
18pub mod bounds;
19
20use std::collections::{BTreeMap, BTreeSet, VecDeque};
21use std::path::PathBuf;
22
23use async_trait::async_trait;
24use awp_types::{Bound, ContentId, ContentItem, ContentKind, ContentState, LanguageTag};
25use chrono::{DateTime, NaiveDate, Utc};
26use serde::{Deserialize, Serialize};
27use serde_json::Value;
28use tokio::sync::Mutex;
29
30use crate::content::SiteConfig;
31use crate::error::{Result, SiteError};
32use crate::lanes::{Lane, lane_of};
33
34/// One record of a feed delivery: a supplier row, a point-of-sale update, a wire item.
35#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
36#[serde(transparent)]
37pub struct FeedRecord(pub BTreeMap<String, Value>);
38
39impl FeedRecord {
40    /// A record from `(column, value)` pairs.
41    pub fn new(pairs: impl IntoIterator<Item = (impl Into<String>, Value)>) -> Self {
42        Self(pairs.into_iter().map(|(k, v)| (k.into(), v)).collect())
43    }
44}
45
46/// Delivers feed records (spec 3.5 §7.8.2 "Imports and feeds").
47///
48/// Each pull is one delivery: one reviewable change set, checked against the feed's bounds
49/// as a whole. Implementations run [`content_source_conformance`].
50#[async_trait]
51pub trait ContentSource: Send + Sync {
52    /// The feed's name, as the owner configured it.
53    fn name(&self) -> &str;
54
55    /// The next delivery's records; empty when nothing new arrived.
56    ///
57    /// # Errors
58    ///
59    /// Returns an error when the source cannot be read.
60    async fn pull(&self) -> Result<Vec<FeedRecord>>;
61}
62
63/// A source the caller pushes deliveries into, such as a webhook receiver; each pull drains
64/// the oldest delivery.
65///
66/// # Example
67///
68/// ```rust
69/// use adk_site::feed::{ContentSource, FeedRecord, InMemorySource};
70///
71/// # #[tokio::main(flavor = "current_thread")]
72/// # async fn main() -> adk_site::Result<()> {
73/// let source = InMemorySource::new("supplier");
74/// source.deliver(vec![FeedRecord::new([("sku", "A1".into()), ("price", 10.into())])]).await;
75/// assert_eq!(source.pull().await?.len(), 1);
76/// assert!(source.pull().await?.is_empty());
77/// # Ok(())
78/// # }
79/// ```
80#[derive(Debug)]
81pub struct InMemorySource {
82    name: String,
83    deliveries: Mutex<VecDeque<Vec<FeedRecord>>>,
84}
85
86impl InMemorySource {
87    /// An empty source named `name`.
88    pub fn new(name: impl Into<String>) -> Self {
89        Self { name: name.into(), deliveries: Mutex::new(VecDeque::new()) }
90    }
91
92    /// Queues one delivery.
93    pub async fn deliver(&self, records: Vec<FeedRecord>) {
94        self.deliveries.lock().await.push_back(records);
95    }
96}
97
98#[async_trait]
99impl ContentSource for InMemorySource {
100    fn name(&self) -> &str {
101        &self.name
102    }
103
104    async fn pull(&self) -> Result<Vec<FeedRecord>> {
105        Ok(self.deliveries.lock().await.pop_front().unwrap_or_default())
106    }
107}
108
109/// A CSV export read whole at each pull: the first row names the columns; values are strings
110/// that the mapping's types parse (RFC 4180 quoting).
111///
112/// # Example
113///
114/// ```rust
115/// use adk_site::feed::{ContentSource, CsvFileSource};
116///
117/// # #[tokio::main(flavor = "current_thread")]
118/// # async fn main() -> adk_site::Result<()> {
119/// let dir = tempfile::tempdir().unwrap();
120/// let path = dir.path().join("stock.csv");
121/// std::fs::write(&path, "sku,price\nA1,\"1,250\"\n").unwrap();
122/// let records = CsvFileSource::new("export", &path).pull().await?;
123/// assert_eq!(records[0].0["price"], "1,250");
124/// # Ok(())
125/// # }
126/// ```
127#[derive(Debug, Clone)]
128pub struct CsvFileSource {
129    name: String,
130    path: PathBuf,
131}
132
133impl CsvFileSource {
134    /// A source reading `path`.
135    pub fn new(name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
136        Self { name: name.into(), path: path.into() }
137    }
138}
139
140#[async_trait]
141impl ContentSource for CsvFileSource {
142    fn name(&self) -> &str {
143        &self.name
144    }
145
146    async fn pull(&self) -> Result<Vec<FeedRecord>> {
147        let text = tokio::fs::read_to_string(&self.path)
148            .await
149            .map_err(|e| SiteError::io(&self.path, e))?;
150        parse_csv(&text).map_err(|message| SiteError::InvalidContent {
151            path: self.path.display().to_string(),
152            message,
153        })
154    }
155}
156
157/// Parses CSV text with a header row into records (RFC 4180).
158///
159/// # Errors
160///
161/// A message for an unterminated quote or a row longer than the header.
162pub fn parse_csv(text: &str) -> std::result::Result<Vec<FeedRecord>, String> {
163    let mut rows: Vec<Vec<String>> = Vec::new();
164    let mut row = Vec::new();
165    let mut field = String::new();
166    let mut quoted = false;
167    let mut chars = text.chars().peekable();
168    let mut any = false;
169    while let Some(c) = chars.next() {
170        any = true;
171        if quoted {
172            match c {
173                '"' if chars.peek() == Some(&'"') => {
174                    chars.next();
175                    field.push('"');
176                }
177                '"' => quoted = false,
178                other => field.push(other),
179            }
180            continue;
181        }
182        match c {
183            '"' if field.is_empty() => quoted = true,
184            ',' => row.push(std::mem::take(&mut field)),
185            '\r' if chars.peek() == Some(&'\n') => {}
186            '\n' => {
187                row.push(std::mem::take(&mut field));
188                rows.push(std::mem::take(&mut row));
189                any = false;
190            }
191            other => field.push(other),
192        }
193    }
194    if quoted {
195        return Err("a quoted field is not closed".into());
196    }
197    if any {
198        row.push(field);
199        rows.push(row);
200    }
201    let mut rows = rows.into_iter().filter(|r| !(r.len() == 1 && r[0].is_empty()));
202    let Some(header) = rows.next() else { return Ok(Vec::new()) };
203    rows.enumerate()
204        .map(|(index, row)| {
205            if row.len() > header.len() {
206                return Err(format!("row {} has more fields than the header", index + 2));
207            }
208            Ok(FeedRecord(header.iter().cloned().zip(row.into_iter().map(Value::String)).collect()))
209        })
210        .collect()
211}
212
213/// The type a mapped field must parse as.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum FieldType {
218    /// A whole number.
219    Integer,
220    /// A number; strings with thousands separators (`1,250.50`) parse.
221    Number,
222    /// Text.
223    Text,
224    /// `true`, `false`, `1`, `0`, `yes`, `no`.
225    Boolean,
226    /// A calendar date, `YYYY-MM-DD`, kept as written.
227    Date,
228    /// An RFC 3339 time, normalised to UTC.
229    Timestamp,
230}
231
232/// A unit conversion applied to a number after parsing: the item's value is the record's
233/// times `factor`.
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct Unit {
237    /// The record's unit, such as `cents`.
238    pub from: String,
239    /// The item's unit, such as `KES`.
240    pub to: String,
241    /// The multiplier from `from` to `to`.
242    pub factor: f64,
243}
244
245/// How one item field is filled from a record.
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase")]
248pub struct FieldMapping {
249    /// The record column.
250    pub from: String,
251    /// The type it must parse as.
252    pub ty: FieldType,
253    /// A conversion for numbers.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub unit: Option<Unit>,
256    /// A bound on the converted value; breaking it holds the whole delivery (A-I27).
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub bound: Option<Bound>,
259    /// Whether every record must carry the column.
260    #[serde(default)]
261    pub required: bool,
262}
263
264impl FieldMapping {
265    /// A mapping of column `from` as `ty`, optional, without unit or bound.
266    pub fn new(from: impl Into<String>, ty: FieldType) -> Self {
267        Self { from: from.into(), ty, unit: None, bound: None, required: false }
268    }
269
270    /// Converts numbers with `unit`.
271    #[must_use]
272    pub fn unit(mut self, unit: Unit) -> Self {
273        self.unit = Some(unit);
274        self
275    }
276
277    /// Bounds the converted value.
278    #[must_use]
279    pub fn bound(mut self, bound: Bound) -> Self {
280        self.bound = Some(bound);
281        self
282    }
283
284    /// Requires the column in every record.
285    #[must_use]
286    pub fn required(mut self) -> Self {
287        self.required = true;
288        self
289    }
290}
291
292/// How a feed's records become item fields: declared types, units and bounds, and no model
293/// (spec 3.5 §7.8.3 "Model-free updates").
294///
295/// # Example
296///
297/// ```rust
298/// use adk_site::content::SiteConfig;
299/// use adk_site::feed::{FeedMapping, FeedRecord, FieldMapping, FieldType, Unit};
300/// use awp_types::ContentKind;
301///
302/// let mapping = FeedMapping::new("supplier", ContentKind::Product, "en".parse().unwrap(), "sku")
303///     .field("price", FieldMapping::new("price_cents", FieldType::Number)
304///         .unit(Unit { from: "cents".into(), to: "KES".into(), factor: 0.01 }))
305///     .field("stock", FieldMapping::new("qty", FieldType::Integer));
306/// let record = FeedRecord::new([("sku", "A1".into()), ("price_cents", "125000".into()), ("qty", 7.into())]);
307/// let mapped = mapping.map(&record, chrono::Utc::now()).unwrap();
308/// assert_eq!(mapped.id.0, "A1");
309/// assert_eq!(mapped.fields["price"], 1250.0);
310/// assert_eq!(mapped.fields["stock"], 7);
311/// ```
312#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct FeedMapping {
315    /// The feed's name.
316    pub feed: String,
317    /// The kind of the items it updates: its collection.
318    pub kind: ContentKind,
319    /// The language of the items it updates.
320    pub language: LanguageTag,
321    /// The column holding each record's key.
322    pub key: String,
323    /// Prepended to the key to make the item id.
324    #[serde(default)]
325    pub id_prefix: String,
326    /// Item field → how it is filled.
327    pub fields: BTreeMap<String, FieldMapping>,
328    /// Whether a record for an unknown key creates an item; otherwise it is reported and
329    /// skipped.
330    #[serde(default)]
331    pub create: bool,
332}
333
334/// A record mapped to item fields.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct MappedRecord {
338    /// The item.
339    pub id: ContentId,
340    /// The record's key.
341    pub key: String,
342    /// Field → converted value.
343    pub fields: BTreeMap<String, Value>,
344}
345
346/// Why a record could not be mapped or broke a bound.
347#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase")]
349pub struct RecordProblem {
350    /// The record's key, when it has one.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub key: Option<String>,
353    /// The item field, when the problem is a field's.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub field: Option<String>,
356    /// What is wrong.
357    pub message: String,
358}
359
360impl FeedMapping {
361    /// A mapping with no fields yet.
362    pub fn new(
363        feed: impl Into<String>,
364        kind: ContentKind,
365        language: LanguageTag,
366        key: impl Into<String>,
367    ) -> Self {
368        Self {
369            feed: feed.into(),
370            kind,
371            language,
372            key: key.into(),
373            id_prefix: String::new(),
374            fields: BTreeMap::new(),
375            create: false,
376        }
377    }
378
379    /// Fills item field `field` with `mapping`.
380    #[must_use]
381    pub fn field(mut self, field: impl Into<String>, mapping: FieldMapping) -> Self {
382        self.fields.insert(field.into(), mapping);
383        self
384    }
385
386    /// Prefixes item ids with `prefix`.
387    #[must_use]
388    pub fn id_prefix(mut self, prefix: impl Into<String>) -> Self {
389        self.id_prefix = prefix.into();
390        self
391    }
392
393    /// Lets records for unknown keys create items.
394    #[must_use]
395    pub fn creating(mut self) -> Self {
396        self.create = true;
397        self
398    }
399
400    /// Checks the mapping against the site's lanes: streams are written by the edge, not by
401    /// feeds.
402    ///
403    /// # Errors
404    ///
405    /// [`SiteError::InvalidConfig`] for a mapping with no fields or one that fills a stream
406    /// field.
407    pub fn validate(&self, config: &SiteConfig) -> Result<()> {
408        if self.fields.is_empty() {
409            return Err(SiteError::InvalidConfig(format!(
410                "feed '{}' maps no fields; map at least one",
411                self.feed
412            )));
413        }
414        for field in self.fields.keys() {
415            if lane_of(config, self.kind, &[], field) == Lane::Stream {
416                return Err(SiteError::InvalidConfig(format!(
417                    "feed '{}' fills the stream field '{field}'; streams are written by the edge, so map it to another field",
418                    self.feed
419                )));
420            }
421        }
422        Ok(())
423    }
424
425    /// Maps one record. `now` anchors date bounds.
426    ///
427    /// # Errors
428    ///
429    /// A [`RecordProblem`] for a missing key or required column, a value of the wrong type,
430    /// or a bound the converted value breaks.
431    pub fn map(
432        &self,
433        record: &FeedRecord,
434        now: DateTime<Utc>,
435    ) -> std::result::Result<MappedRecord, RecordProblem> {
436        let key = match record.0.get(&self.key) {
437            Some(Value::String(s)) if !s.trim().is_empty() => s.trim().to_string(),
438            Some(Value::Number(n)) => n.to_string(),
439            _ => {
440                return Err(RecordProblem {
441                    key: None,
442                    field: None,
443                    message: format!("the record has no key in column '{}'", self.key),
444                });
445            }
446        };
447        let problem = |field: &str, message: String| RecordProblem {
448            key: Some(key.clone()),
449            field: Some(field.to_string()),
450            message,
451        };
452        let mut fields = BTreeMap::new();
453        for (field, mapping) in &self.fields {
454            let raw = match record.0.get(&mapping.from) {
455                None | Some(Value::Null) => {
456                    if mapping.required {
457                        return Err(problem(
458                            field,
459                            format!("column '{}' is missing", mapping.from),
460                        ));
461                    }
462                    continue;
463                }
464                Some(Value::String(s)) if s.trim().is_empty() && !mapping.required => continue,
465                Some(raw) => raw,
466            };
467            let value = parse(raw, mapping.ty).ok_or_else(|| {
468                let ty = format!("{:?}", mapping.ty).to_lowercase();
469                problem(field, format!("{raw} is not a valid {ty}"))
470            })?;
471            let value = match (&mapping.unit, value.as_f64()) {
472                (Some(unit), Some(number)) => number_value(number * unit.factor, mapping.ty),
473                _ => value,
474            };
475            if let Some(bound) = &mapping.bound
476                && !within(bound, &value, now)
477            {
478                return Err(problem(field, format!("{value} breaks the bound {bound:?}")));
479            }
480            fields.insert(field.clone(), value);
481        }
482        Ok(MappedRecord { id: ContentId(format!("{}{key}", self.id_prefix)), key, fields })
483    }
484
485    /// Compares mapped records with the items the site holds and returns the changes, each
486    /// changed field in its lane (spec 3.5 §7.8.3).
487    ///
488    /// `current` holds the site's items by id. A record that changes nothing produces no
489    /// change; a record for an unknown key creates an item only when the mapping allows it.
490    pub fn changes(
491        &self,
492        config: &SiteConfig,
493        records: &[MappedRecord],
494        current: &BTreeMap<ContentId, ContentItem>,
495        now: DateTime<Utc>,
496    ) -> FeedChanges {
497        let mut changes = FeedChanges::default();
498        let mut seen = BTreeSet::new();
499        for record in records.iter().rev() {
500            // The last record for a key in a delivery wins.
501            if !seen.insert(record.id.clone()) {
502                continue;
503            }
504            let existing = current.get(&record.id);
505            let base = match existing {
506                Some(item) => item.clone(),
507                None if self.create => self.new_item(record),
508                None => {
509                    changes.unknown.push(record.key.clone());
510                    continue;
511                }
512            };
513            let mut live = BTreeMap::new();
514            let mut released = base.clone();
515            let mut release_changed = existing.is_none();
516            for (field, value) in &record.fields {
517                if base.fields.get(field) == Some(value) {
518                    continue;
519                }
520                match lane_of(config, base.kind, &base.volatile, field) {
521                    Lane::Live => {
522                        live.insert(field.clone(), value.clone());
523                    }
524                    Lane::Release | Lane::Stream => {
525                        released.fields.insert(field.clone(), value.clone());
526                        release_changed = true;
527                    }
528                }
529            }
530            if !live.is_empty() {
531                changes.live.push(LiveChange { id: record.id.clone(), fields: live });
532            }
533            if release_changed {
534                released.fields.insert(
535                    "updatedAt".into(),
536                    now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true).into(),
537                );
538                changes.release.push(ReleaseChange { before: existing.cloned(), after: released });
539            }
540        }
541        changes.live.reverse();
542        changes.release.reverse();
543        changes.unknown.reverse();
544        changes
545    }
546
547    fn new_item(&self, record: &MappedRecord) -> ContentItem {
548        ContentItem {
549            id: record.id.clone(),
550            kind: self.kind,
551            slug: slug(&record.key),
552            language: self.language.clone(),
553            fields: BTreeMap::new(),
554            volatile: Vec::new(),
555            body: None,
556            media: Vec::new(),
557            sources: Vec::new(),
558            schedule: None,
559            state: ContentState::Published,
560        }
561    }
562}
563
564/// New live values for one item.
565#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
566#[serde(rename_all = "camelCase")]
567pub struct LiveChange {
568    /// The item.
569    pub id: ContentId,
570    /// Field → new value.
571    pub fields: BTreeMap<String, Value>,
572}
573
574/// A new released version of one item.
575#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
576#[serde(rename_all = "camelCase")]
577pub struct ReleaseChange {
578    /// The version the site holds; `None` for a new item.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub before: Option<ContentItem>,
581    /// The new version.
582    pub after: ContentItem,
583}
584
585/// What one delivery changes, by lane.
586#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
587#[serde(rename_all = "camelCase")]
588pub struct FeedChanges {
589    /// Live values for the edge; never released.
590    pub live: Vec<LiveChange>,
591    /// New item versions for the batcher.
592    pub release: Vec<ReleaseChange>,
593    /// Keys of records for items the site does not have.
594    #[serde(default, skip_serializing_if = "Vec::is_empty")]
595    pub unknown: Vec<String>,
596}
597
598impl FeedChanges {
599    /// The items the delivery changes in any lane.
600    pub fn changed_items(&self) -> BTreeSet<ContentId> {
601        self.live
602            .iter()
603            .map(|c| c.id.clone())
604            .chain(self.release.iter().map(|c| c.after.id.clone()))
605            .collect()
606    }
607
608    /// Field updates in the delivery, live and released.
609    pub fn field_updates(&self) -> u64 {
610        let live: usize = self.live.iter().map(|c| c.fields.len()).sum();
611        let released: usize = self
612            .release
613            .iter()
614            .map(|c| {
615                c.after
616                    .fields
617                    .iter()
618                    .filter(|(k, v)| {
619                        k.as_str() != "updatedAt"
620                            && c.before.as_ref().is_none_or(|b| b.fields.get(*k) != Some(*v))
621                    })
622                    .count()
623            })
624            .sum();
625        (live + released) as u64
626    }
627}
628
629/// A URL slug for a feed key: lowercase letters and digits, other runs as `-`.
630fn slug(key: &str) -> String {
631    let mut out = String::new();
632    for c in key.chars().flat_map(char::to_lowercase) {
633        if c.is_ascii_alphanumeric() {
634            out.push(c);
635        } else if !out.ends_with('-') {
636            out.push('-');
637        }
638    }
639    let out = out.trim_matches('-').to_string();
640    if out.is_empty() { "item".into() } else { out }
641}
642
643fn number_value(number: f64, ty: FieldType) -> Value {
644    if ty == FieldType::Integer || (number.fract() == 0.0 && number.abs() < 9.0e15) {
645        Value::from(number as i64)
646    } else {
647        serde_json::Number::from_f64(number).map_or(Value::Null, Value::Number)
648    }
649}
650
651fn parse(raw: &Value, ty: FieldType) -> Option<Value> {
652    let text = |raw: &Value| match raw {
653        Value::String(s) => Some(s.trim().to_string()),
654        Value::Number(n) => Some(n.to_string()),
655        Value::Bool(b) => Some(b.to_string()),
656        _ => None,
657    };
658    match ty {
659        FieldType::Integer => match raw {
660            Value::Number(n) => n.as_i64().map(Value::from),
661            _ => text(raw)?.replace(',', "").parse::<i64>().ok().map(Value::from),
662        },
663        FieldType::Number => {
664            let number = match raw {
665                Value::Number(n) => n.as_f64()?,
666                _ => text(raw)?.replace(',', "").parse::<f64>().ok()?,
667            };
668            number.is_finite().then(|| number_value(number, ty))
669        }
670        FieldType::Text => text(raw).map(Value::String),
671        FieldType::Boolean => match raw {
672            Value::Bool(b) => Some(Value::Bool(*b)),
673            _ => match text(raw)?.to_ascii_lowercase().as_str() {
674                "true" | "1" | "yes" => Some(Value::Bool(true)),
675                "false" | "0" | "no" => Some(Value::Bool(false)),
676                _ => None,
677            },
678        },
679        FieldType::Date => {
680            let text = text(raw)?;
681            NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok().map(|_| Value::String(text))
682        }
683        FieldType::Timestamp => DateTime::parse_from_rfc3339(&text(raw)?).ok().map(|d| {
684            Value::String(d.with_timezone(&Utc).to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
685        }),
686    }
687}
688
689/// Whether `value` is within `bound`: a number within a range, a date or time within the
690/// days either side of `now`.
691pub(crate) fn within(bound: &Bound, value: &Value, now: DateTime<Utc>) -> bool {
692    if let Some(number) = value.as_f64() {
693        return bound.allows_number(number);
694    }
695    let Some(text) = value.as_str() else { return false };
696    let at = DateTime::parse_from_rfc3339(text).map(|d| d.with_timezone(&Utc)).ok().or_else(|| {
697        NaiveDate::parse_from_str(text, "%Y-%m-%d")
698            .ok()
699            .and_then(|d| d.and_hms_opt(0, 0, 0))
700            .map(|d| d.and_utc())
701    });
702    at.is_some_and(|at| bound.allows_date(at, now))
703}
704
705/// Checks a source against its contract: `deliver` puts `records` where the source reads
706/// them, and the next pull returns them in order with their values as strings or numbers.
707///
708/// # Panics
709///
710/// Panics with the failed expectation.
711pub async fn content_source_conformance<F, Fut>(deliver: F)
712where
713    F: Fn(Vec<FeedRecord>) -> Fut,
714    Fut: std::future::Future<Output = std::sync::Arc<dyn ContentSource>>,
715{
716    let records = vec![
717        FeedRecord::new([("sku", Value::from("A1")), ("price", Value::from("12.50"))]),
718        FeedRecord::new([("sku", Value::from("B2")), ("price", Value::from("7"))]),
719        FeedRecord::new([("sku", Value::from("C, \"3\"")), ("price", Value::from("1,000"))]),
720    ];
721    let source = deliver(records.clone()).await;
722    assert!(!source.name().is_empty(), "a source has a name");
723    let pulled = source.pull().await.expect("pull");
724    let as_text = |r: &FeedRecord| -> BTreeMap<String, String> {
725        r.0.iter()
726            .map(|(k, v)| (k.clone(), v.as_str().map_or_else(|| v.to_string(), str::to_string)))
727            .collect()
728    };
729    assert_eq!(
730        pulled.iter().map(as_text).collect::<Vec<_>>(),
731        records.iter().map(as_text).collect::<Vec<_>>(),
732        "the delivery's records, in order"
733    );
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739    use crate::lanes::KindLanes;
740
741    fn mapping() -> FeedMapping {
742        FeedMapping::new("supplier", ContentKind::Product, "en".parse().unwrap(), "sku")
743            .field(
744                "price",
745                FieldMapping::new("price", FieldType::Number).required().bound(Bound::Range {
746                    minimum: None,
747                    exclusive_minimum: Some(0.0),
748                    maximum: None,
749                    exclusive_maximum: None,
750                }),
751            )
752            .field("stock", FieldMapping::new("qty", FieldType::Integer))
753            .field("restock", FieldMapping::new("next", FieldType::Date))
754    }
755
756    fn config() -> SiteConfig {
757        let mut config = SiteConfig::new("Shop", "shop.example", vec!["en".parse().unwrap()]);
758        config.lanes.insert(
759            ContentKind::Product,
760            KindLanes { volatile: vec!["stock".into()], ..KindLanes::default() },
761        );
762        config
763    }
764
765    fn now() -> DateTime<Utc> {
766        DateTime::parse_from_rfc3339("2026-10-25T09:00:00Z").unwrap().with_timezone(&Utc)
767    }
768
769    #[test]
770    fn records_map_through_types_units_and_bounds() {
771        let m = mapping();
772        let ok = FeedRecord::new([
773            ("sku", "A1".into()),
774            ("price", "1,250.50".into()),
775            ("qty", "7".into()),
776            ("next", "2026-11-01".into()),
777        ]);
778        let mapped = m.map(&ok, now()).unwrap();
779        assert_eq!(mapped.fields["price"], 1250.5);
780        assert_eq!(mapped.fields["stock"], 7);
781        assert_eq!(mapped.fields["restock"], "2026-11-01");
782        let zero = FeedRecord::new([("sku", "A1".into()), ("price", 0.into())]);
783        assert!(m.map(&zero, now()).unwrap_err().message.contains("bound"));
784        let text = FeedRecord::new([("sku", "A1".into()), ("price", "ten".into())]);
785        assert_eq!(m.map(&text, now()).unwrap_err().field.as_deref(), Some("price"));
786        let missing = FeedRecord::new([("sku", "A1".into())]);
787        assert!(m.map(&missing, now()).unwrap_err().message.contains("missing"));
788        assert!(m.map(&FeedRecord::default(), now()).unwrap_err().key.is_none());
789    }
790
791    #[test]
792    fn changes_sort_fields_into_lanes() {
793        let config = config();
794        let m = mapping();
795        let item = |price: f64, stock: i64| ContentItem {
796            id: "A1".into(),
797            kind: ContentKind::Product,
798            slug: "a1".into(),
799            language: "en".parse().unwrap(),
800            fields: BTreeMap::from([
801                ("price".to_string(), Value::from(price)),
802                ("stock".to_string(), Value::from(stock)),
803            ]),
804            volatile: Vec::new(),
805            body: None,
806            media: Vec::new(),
807            sources: Vec::new(),
808            schedule: None,
809            state: ContentState::Published,
810        };
811        let current = BTreeMap::from([(ContentId::from("A1"), item(10.5, 3))]);
812        let stock_only = MappedRecord {
813            id: "A1".into(),
814            key: "A1".into(),
815            fields: BTreeMap::from([("price".into(), 10.5.into()), ("stock".into(), 2.into())]),
816        };
817        let changes = m.changes(&config, &[stock_only], &current, now());
818        assert!(changes.release.is_empty(), "a stock change never makes a release");
819        assert_eq!(changes.live[0].fields["stock"], 2);
820        assert_eq!(changes.field_updates(), 1);
821
822        let price = MappedRecord {
823            id: "A1".into(),
824            key: "A1".into(),
825            fields: BTreeMap::from([("price".into(), 11.into())]),
826        };
827        let unknown = MappedRecord { id: "Z9".into(), key: "Z9".into(), fields: BTreeMap::new() };
828        let changes = m.changes(&config, &[price, unknown.clone()], &current, now());
829        assert_eq!(changes.release.len(), 1);
830        assert_eq!(changes.release[0].after.fields["price"], 11);
831        assert_eq!(changes.release[0].after.fields["updatedAt"], "2026-10-25T09:00:00Z");
832        assert_eq!(changes.unknown, vec!["Z9".to_string()]);
833        let created = m.clone().creating().changes(&config, &[unknown], &current, now());
834        assert_eq!(created.release[0].before, None);
835        assert_eq!(created.release[0].after.slug, "z9");
836    }
837
838    #[test]
839    fn mappings_never_fill_streams() {
840        let mut config = config();
841        config.lanes.insert(
842            ContentKind::Article,
843            KindLanes { stream: vec!["entries".into()], ..KindLanes::default() },
844        );
845        let m = FeedMapping::new("wire", ContentKind::Article, "en".parse().unwrap(), "id")
846            .field("entries", FieldMapping::new("text", FieldType::Text));
847        assert!(m.validate(&config).is_err());
848        assert!(mapping().validate(&config).is_ok());
849    }
850
851    #[test]
852    fn csv_parses_quotes_and_line_endings() {
853        let records = parse_csv("sku,name\r\nA1,\"Panel, \"\"400\"\" W\"\r\nB2,\n\n").unwrap();
854        assert_eq!(records.len(), 2);
855        assert_eq!(records[0].0["name"], "Panel, \"400\" W");
856        assert_eq!(records[1].0["name"], "");
857        assert!(parse_csv("a\n\"open").is_err());
858        assert!(parse_csv("a\n1,2").is_err());
859        assert!(parse_csv("").unwrap().is_empty());
860    }
861}