1pub 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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
36#[serde(transparent)]
37pub struct FeedRecord(pub BTreeMap<String, Value>);
38
39impl FeedRecord {
40 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#[async_trait]
51pub trait ContentSource: Send + Sync {
52 fn name(&self) -> &str;
54
55 async fn pull(&self) -> Result<Vec<FeedRecord>>;
61}
62
63#[derive(Debug)]
81pub struct InMemorySource {
82 name: String,
83 deliveries: Mutex<VecDeque<Vec<FeedRecord>>>,
84}
85
86impl InMemorySource {
87 pub fn new(name: impl Into<String>) -> Self {
89 Self { name: name.into(), deliveries: Mutex::new(VecDeque::new()) }
90 }
91
92 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#[derive(Debug, Clone)]
128pub struct CsvFileSource {
129 name: String,
130 path: PathBuf,
131}
132
133impl CsvFileSource {
134 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
157pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum FieldType {
218 Integer,
220 Number,
222 Text,
224 Boolean,
226 Date,
228 Timestamp,
230}
231
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct Unit {
237 pub from: String,
239 pub to: String,
241 pub factor: f64,
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase")]
248pub struct FieldMapping {
249 pub from: String,
251 pub ty: FieldType,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub unit: Option<Unit>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub bound: Option<Bound>,
259 #[serde(default)]
261 pub required: bool,
262}
263
264impl FieldMapping {
265 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 #[must_use]
272 pub fn unit(mut self, unit: Unit) -> Self {
273 self.unit = Some(unit);
274 self
275 }
276
277 #[must_use]
279 pub fn bound(mut self, bound: Bound) -> Self {
280 self.bound = Some(bound);
281 self
282 }
283
284 #[must_use]
286 pub fn required(mut self) -> Self {
287 self.required = true;
288 self
289 }
290}
291
292#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct FeedMapping {
315 pub feed: String,
317 pub kind: ContentKind,
319 pub language: LanguageTag,
321 pub key: String,
323 #[serde(default)]
325 pub id_prefix: String,
326 pub fields: BTreeMap<String, FieldMapping>,
328 #[serde(default)]
331 pub create: bool,
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct MappedRecord {
338 pub id: ContentId,
340 pub key: String,
342 pub fields: BTreeMap<String, Value>,
344}
345
346#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase")]
349pub struct RecordProblem {
350 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub key: Option<String>,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub field: Option<String>,
356 pub message: String,
358}
359
360impl FeedMapping {
361 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 #[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 #[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 #[must_use]
395 pub fn creating(mut self) -> Self {
396 self.create = true;
397 self
398 }
399
400 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 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
566#[serde(rename_all = "camelCase")]
567pub struct LiveChange {
568 pub id: ContentId,
570 pub fields: BTreeMap<String, Value>,
572}
573
574#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
576#[serde(rename_all = "camelCase")]
577pub struct ReleaseChange {
578 #[serde(default, skip_serializing_if = "Option::is_none")]
580 pub before: Option<ContentItem>,
581 pub after: ContentItem,
583}
584
585#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
587#[serde(rename_all = "camelCase")]
588pub struct FeedChanges {
589 pub live: Vec<LiveChange>,
591 pub release: Vec<ReleaseChange>,
593 #[serde(default, skip_serializing_if = "Vec::is_empty")]
595 pub unknown: Vec<String>,
596}
597
598impl FeedChanges {
599 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 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
629fn 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
689pub(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
705pub 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], ¤t, 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()], ¤t, 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], ¤t, 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}