use std::any::{Any, TypeId};
use std::marker::PhantomData;
use std::sync::Arc;
use async_trait::async_trait;
use laravel::db::col;
use laravel::model::Model;
use laravel::stream::StreamExt;
use laravel::time::{Timestamp, civil};
use crate::record::Record;
use crate::registration::Registration;
use crate::source::Page;
use crate::value::Attr;
#[async_trait]
pub trait Tracked: Send + Sync {
fn model_name(&self) -> &'static str;
fn model_type(&self) -> TypeId;
fn describe(&self) -> String;
fn as_any(&self) -> &dyn Any;
fn has_url(&self) -> bool;
fn publish_column(&self) -> Option<String>;
fn change_column(&self) -> Option<String>;
async fn changed_since(&self, since: Timestamp, until: Timestamp) -> laravel::Result<Vec<Page>>;
}
#[async_trait]
pub trait UrlSink: Send {
async fn send(&mut self, urls: Vec<String>) -> laravel::Result<usize>;
}
#[derive(Debug, Clone)]
pub struct ScanOptions {
pub chunk: u64,
pub batch: usize,
pub limit: Option<u64>,
pub dry_run: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Scan {
pub seen: u64,
pub matched: u64,
pub submitted: u64,
}
#[async_trait]
pub trait ModelDriver: Send + Sync {
fn model_name(&self) -> &'static str;
fn type_name(&self) -> &'static str;
async fn count(&self, limit: Option<u64>) -> laravel::Result<u64>;
async fn scan(&self, registry: &Registry, options: &ScanOptions, sink: &mut dyn UrlSink) -> laravel::Result<Scan>;
}
#[derive(Default, Clone)]
pub struct Registry {
tracked: Vec<Arc<dyn Tracked>>,
drivers: Vec<(TypeId, Arc<dyn ModelDriver>)>,
}
impl Registry {
pub fn add<M: Model>(&mut self, registration: Registration<M>) {
let id = TypeId::of::<M>();
if !self.drivers.iter().any(|(existing, _)| *existing == id) {
self.drivers.push((id, Arc::new(Driver::<M>(PhantomData))));
}
self.tracked.push(Arc::new(registration));
}
pub fn tracks<M: Model>(&self) -> bool {
self.tracked
.iter()
.any(|tracked| tracked.model_type() == TypeId::of::<M>())
}
pub fn for_model<M: Model>(&self) -> Vec<&Registration<M>> {
self.tracked
.iter()
.filter_map(|tracked| tracked.as_any().downcast_ref::<Registration<M>>())
.collect()
}
pub fn tracked(&self) -> &[Arc<dyn Tracked>] {
&self.tracked
}
pub fn driver(&self, name: &str) -> Option<Arc<dyn ModelDriver>> {
self.drivers
.iter()
.map(|(_, driver)| driver)
.find(|driver| driver.type_name() == name || driver.model_name().eq_ignore_ascii_case(name))
.cloned()
}
pub fn is_empty(&self) -> bool {
self.tracked.is_empty()
}
pub fn validate(&self) -> laravel::Result<()> {
for tracked in &self.tracked {
if !tracked.has_url() {
return Err(laravel::Error::msg(format!(
"No IndexNow URL resolver defined for [{}]. Call url() or url_template() on the registration, or give it a policy.",
tracked.model_name()
)));
}
if tracked.change_column().is_some() && tracked.publish_column().is_none() {
return Err(laravel::Error::msg(format!(
"changes_at() on [{}] needs publishes_at(): without it the registration is not a source.",
tracked.model_name()
)));
}
}
Ok(())
}
}
#[async_trait]
impl<M: Model> Tracked for Registration<M> {
fn model_name(&self) -> &'static str {
M::META.name
}
fn model_type(&self) -> TypeId {
TypeId::of::<M>()
}
fn describe(&self) -> String {
Registration::describe(self)
}
fn as_any(&self) -> &dyn Any {
self
}
fn has_url(&self) -> bool {
Registration::has_url(self)
}
fn publish_column(&self) -> Option<String> {
Registration::publish_column(self).map(str::to_owned)
}
fn change_column(&self) -> Option<String> {
Registration::change_column(self).map(str::to_owned)
}
async fn changed_since(&self, since: Timestamp, until: Timestamp) -> laravel::Result<Vec<Page>> {
let columns: Vec<String> = [self.publish_column(), self.change_column()]
.into_iter()
.flatten()
.map(str::to_owned)
.collect();
let mut window = None;
for column in &columns {
let within = col(column).ge(since) & col(column).le(until);
window = Some(match window {
Some(existing) => existing | within,
None => within,
});
}
let Some(window) = window else {
return Ok(Vec::new());
};
let mut rows = laravel::model::__query::<M>().filter(window).lazy_by_id(500);
let mut pages = Vec::new();
while let Some(row) = rows.next().await {
let row = row?;
let record = Record::of(&row);
let Some(changed_at) = columns
.iter()
.filter_map(|column| instant(record.get(column)))
.filter(|date| *date >= since && *date <= until)
.max()
else {
continue;
};
if !self.passes(&record) {
continue;
}
let mut urls: Vec<String> = self.url_of(&row, &record)?.into_iter().collect();
urls.extend(self.affected_urls(&row));
urls.dedup();
for url in urls {
pages.push(Page::new(url, changed_at));
}
}
Ok(pages)
}
}
struct Driver<M>(PhantomData<fn() -> M>);
#[async_trait]
impl<M: Model> ModelDriver for Driver<M> {
fn model_name(&self) -> &'static str {
M::META.name
}
fn type_name(&self) -> &'static str {
std::any::type_name::<M>()
}
async fn count(&self, limit: Option<u64>) -> laravel::Result<u64> {
let count = laravel::model::__query::<M>().count().await?;
Ok(limit.map_or(count, |limit| count.min(limit)))
}
async fn scan(&self, registry: &Registry, options: &ScanOptions, sink: &mut dyn UrlSink) -> laravel::Result<Scan> {
let registrations = registry.for_model::<M>();
let mut scan = Scan::default();
let mut urls: Vec<String> = Vec::new();
let mut marks: Vec<(usize, M)> = Vec::new();
let mut chunks = laravel::model::__query::<M>().chunk_by_id(options.chunk.max(1));
'rows: while let Some(chunk) = chunks.next().await {
for row in chunk? {
scan.seen += 1;
let record = Record::of(&row);
let mut row_urls: Vec<String> = Vec::new();
for (index, registration) in registrations.iter().enumerate() {
if !registration.passes(&record) {
continue;
}
if let Some(url) = registration.url_of(&row, &record)?
&& !row_urls.contains(&url)
{
row_urls.push(url);
}
if registration.has_sets() && !options.dry_run {
marks.push((index, row.clone()));
}
}
if !row_urls.is_empty() {
scan.matched += 1;
urls.extend(row_urls);
}
if urls.len() >= options.batch.max(1) {
scan.submitted += flush(registrations.as_slice(), sink, &mut urls, &mut marks).await?;
}
if options.limit.is_some_and(|limit| scan.seen >= limit) {
break 'rows;
}
}
}
if !urls.is_empty() {
scan.submitted += flush(registrations.as_slice(), sink, &mut urls, &mut marks).await?;
}
Ok(scan)
}
}
async fn flush<M: Model>(
registrations: &[&Registration<M>],
sink: &mut dyn UrlSink,
urls: &mut Vec<String>,
marks: &mut Vec<(usize, M)>,
) -> laravel::Result<u64> {
let sent = sink.send(std::mem::take(urls)).await?;
for (index, row) in std::mem::take(marks) {
registrations[index].apply_set(&row).await?;
}
Ok(sent as u64)
}
pub fn instant(value: &Attr) -> Option<Timestamp> {
match value {
Attr::Time(timestamp) => Some(*timestamp),
Attr::Int(seconds) => Timestamp::from_second(*seconds).ok(),
Attr::Text(text) => text
.parse::<Timestamp>()
.ok()
.or_else(|| {
text.parse::<civil::DateTime>()
.ok()
.and_then(|date| date.in_tz("UTC").ok())
.map(|zoned| zoned.timestamp())
})
.or_else(|| {
text.parse::<civil::Date>()
.ok()
.and_then(|date| date.in_tz("UTC").ok())
.map(|zoned| zoned.timestamp())
}),
_ => None,
}
}