use std::collections::BTreeMap;
use std::path::Path;
use async_trait::async_trait;
use laravel::console::{Console, command, escape_markup};
use laravel::container::Inject;
use laravel::http::client;
use laravel::time::{Timestamp, ToSpan};
use crate::keys::KeyRepository;
use crate::manager::IndexNow;
use crate::result::{RetryableSubmission, SubmissionResult};
use crate::source::Page;
use crate::support::config;
use crate::tracked::{ScanOptions, UrlSink};
const DISABLED: &str = "IndexNow is disabled in this environment. Nothing was submitted.";
const DISABLED_HINT: &str = " See indexnow.enabled and indexnow.environments.";
fn detail(console: &mut Console, label: &str, status: &str) {
let dots = ".".repeat(60usize.saturating_sub(label.chars().count()).max(3));
console.markup(format!(" {} <fg=gray>{dots}</> {status}", escape_markup(label)));
}
fn report(console: &mut Console, result: &SubmissionResult) {
let status = match (result.successful, result.skipped) {
(true, _) => "<fg=green>ok</>",
(_, true) => "<fg=yellow>skipped</>",
_ => "<fg=red>failed</>",
};
detail(console, &format!("{} ({} URLs)", result.host, result.count()), status);
console.line(format!(" {}", result.message));
}
#[command("indexnow:key")]
pub async fn key(
#[arg(long)]
host: Option<String>,
#[arg(long, default_value_t = 32)]
length: usize,
#[arg(long)]
file: bool,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
let keys = manager.keys();
let explicit = host.clone();
let host = host.unwrap_or_else(|| keys.app_host());
if let Some(existing) = keys.for_host(&host) {
console.warn(format!("Host [{host}] already has a key configured: {existing}"));
if !console.is_interactive() {
console.line(" There is no terminal to confirm a new one, so the configured key stays.");
}
if !console.confirm("Generate a new one anyway?").default(false).await? {
console.new_line();
if file {
write_key_file(console, &existing)?;
} else {
console.markup(" Pass <fg=cyan>--file</> to write the configured key to public/.");
console.new_line();
}
return Ok(0);
}
}
let key = KeyRepository::generate(length);
console.new_line();
console.markup(" <fg=green;options=bold>Key generated.</> Set it in the configuration, in src/app.rs:");
console.new_line();
if explicit.is_some() {
console.line(format!(
" config.section_mut::<IndexNowConfig>().keys.insert(\"{host}\".into(), \"{key}\".into());"
));
} else {
console.line(format!(
" config.section_mut::<IndexNowConfig>().key = Some(\"{key}\".into());"
));
}
console.new_line();
console.markup(format!(
" It must be publicly readable at <fg=cyan>{}/{key}.txt</>",
keys.base_url_for(&host)
));
console.markup(" which this package serves for you while <fg=yellow>serve_key_file</> stays enabled.");
console.new_line();
if file {
write_key_file(console, &key)?;
} else {
console.markup(" Pass <fg=cyan>--file</> to write it to public/ as well, so a search engine");
console.line(" can still read it while the application is down for maintenance.");
console.new_line();
}
console.markup(" Then confirm it is reachable with <fg=cyan>indexnow:verify</>");
console.new_line();
Ok(0)
}
fn write_key_file(console: &mut Console, key: &str) -> laravel::Result<()> {
let app = &laravel::config().app;
let path = app.public_path(format!("{key}.txt"));
for stale in stale_key_files(&app.public_path(""), key) {
console.warn(format!(" There is already a key file at public/{stale}"));
console.line(" Delete it once the new key is live, or an old key stays claimable.");
console.new_line();
}
let Some(directory) = path.parent().filter(|directory| directory.is_dir()) else {
console.error(" public/ is not there, so the key file was not written.");
console.new_line();
return Ok(());
};
if let Err(error) = std::fs::write(directory.join(format!("{key}.txt")), key) {
console.error(format!(
" Could not write {}: {error}. Check the permissions.",
path.display()
));
console.new_line();
return Ok(());
}
console.markup(format!(
" <fg=green;options=bold>Written</> to <fg=cyan>public/{key}.txt</>"
));
console.line(" Commit it, or generate it again on the server after deploying.");
console.new_line();
Ok(())
}
fn stale_key_files(public: &Path, current: &str) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(public) else {
return Vec::new();
};
let mut stale: Vec<String> = entries
.filter_map(Result::ok)
.filter_map(|entry| {
let file = entry.file_name().to_string_lossy().into_owned();
let name = file.strip_suffix(".txt")?.to_owned();
if name == current || !KeyRepository::is_valid(&name) {
return None;
}
let contents = std::fs::read_to_string(entry.path()).ok()?;
(contents.trim() == name).then_some(file)
})
.collect();
stale.sort();
stale
}
#[command("indexnow:verify")]
pub async fn verify(
#[arg(long)]
host: Option<String>,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
let keys = manager.keys();
let hosts = host.map_or_else(|| keys.allowed_hosts(), |host| vec![host]);
if hosts.is_empty() {
console.error("No hosts configured. Set the key or the keys of IndexNowConfig first.");
return Ok(1);
}
let mut failed = false;
for host in hosts {
failed = !verify_host(console, &host, &keys).await || failed;
}
Ok(u8::from(failed))
}
async fn verify_host(console: &mut Console, host: &str, keys: &KeyRepository) -> bool {
let Some(key) = keys.for_host(host) else {
detail(console, host, "<fg=red>no key configured</>");
return false;
};
if !KeyRepository::is_valid(&key) {
detail(console, host, "<fg=red>malformed key</>");
console.line(" A key is 8 to 128 characters of letters, numbers and dashes.");
return false;
}
let location = keys.location_for(host, None).unwrap_or_default();
let response = match client::get(&location).timeout(10.seconds()).await {
Ok(response) => response,
Err(error) => {
detail(console, host, "<fg=red>unreachable</>");
console.line(format!(" {location}"));
console.line(format!(" {error}"));
return false;
}
};
if !response.successful() {
detail(
console,
host,
&format!("<fg=red>HTTP {}</>", response.status().as_u16()),
);
console.line(format!(" {location}"));
return false;
}
if response.text().trim() != key {
detail(console, host, "<fg=red>wrong contents</>");
console.line(format!(" {location}"));
console.line(format!(" expected [{key}], found [{}]", response.text().trim()));
return false;
}
detail(console, host, "<fg=green>ok</>");
console.line(format!(" {location}"));
true
}
#[command("indexnow:submit")]
pub async fn submit(
#[arg(required = true)]
url: Vec<String>,
#[arg(long)]
queue: bool,
#[arg(long)]
force: bool,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
if !manager.enabled() {
console.warn(DISABLED);
console.line(DISABLED_HINT);
return Ok(1);
}
if queue {
let count = url.len();
manager.submit(url).await?;
console.info(format!("Queued {count} URL(s)."));
return Ok(0);
}
let results = match manager.submit_now(url, force).await {
Ok(results) => results,
Err(error) => return failure(console, &error),
};
if results.is_empty() {
console.warn("Nothing was submitted: the URLs were filtered out.");
console.line(" Either the host is not allowed, the URL is malformed, or it was submitted recently.");
console.line(" Pass --force to ignore the deduplication window.");
return Ok(1);
}
let mut failed = false;
for result in &results {
report(console, result);
failed = failed || !result.successful;
}
Ok(u8::from(failed))
}
fn failure(console: &mut Console, error: &laravel::Error) -> laravel::Result<u8> {
match error.downcast_ref::<RetryableSubmission>() {
Some(retryable) => {
console.error(format!(
"{} Try again later, or send it through the queue.",
retryable.message
));
Ok(1)
}
None => Err(laravel::Error::msg(error.to_string())),
}
}
#[command("indexnow:sync")]
pub async fn sync(
model: String,
#[arg(long, default_value_t = 500)]
chunk: u64,
#[arg(long, default_value_t = 1000)]
batch: usize,
#[arg(long)]
limit: Option<u64>,
#[arg(long)]
queue: bool,
#[arg(long)]
force: bool,
#[arg(long)]
dry_run: bool,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
let Some(driver) = manager.registry().driver(&model) else {
console.error("That model is not tracked by IndexNow.");
console.line(" Run `indexnow:models` to see the ones that are.");
return Ok(1);
};
if !dry_run && !manager.enabled() {
console.warn(DISABLED);
return Ok(1);
}
let options = ScanOptions {
chunk,
batch,
limit: limit.map(|limit| limit.max(1)),
dry_run,
};
let total = driver.count(options.limit).await?;
let mut sink = Sink {
console,
manager: &manager,
dry_run,
queue,
force,
};
let scan = driver.scan(manager.registry(), &options, &mut sink).await?;
console.new_line();
detail(console, "Rows read", &format!("{} of {total}", scan.seen));
detail(console, "Indexable", &scan.matched.to_string());
detail(
console,
if dry_run { "Would submit" } else { "Submitted" },
&scan.submitted.to_string(),
);
if dry_run {
console.new_line();
console.line(" Nothing left the application, this was a dry run.");
}
console.new_line();
Ok(0)
}
struct Sink<'a> {
console: &'a mut Console,
manager: &'a IndexNow,
dry_run: bool,
queue: bool,
force: bool,
}
#[async_trait]
impl UrlSink for Sink<'_> {
async fn send(&mut self, urls: Vec<String>) -> laravel::Result<usize> {
if self.dry_run {
for url in &urls {
self.console.line(format!(" {url}"));
}
return Ok(urls.len());
}
if self.queue {
let count = urls.len();
self.manager.submit(urls).await?;
return Ok(count);
}
let mut sent = 0;
let results = match self.manager.submit_now(urls, self.force).await {
Ok(results) => results,
Err(error) => match error.downcast_ref::<RetryableSubmission>() {
Some(retryable) => {
self.console
.warn(format!(" {}: {}", retryable.host, retryable.message));
return Ok(0);
}
None => return Err(error),
},
};
for result in results {
if result.successful {
sent += result.count();
} else {
self.console.warn(format!(" {}: {}", result.host, result.message));
}
}
Ok(sent)
}
}
#[command("indexnow:due")]
pub async fn due(
#[arg(long)]
hours: Option<u64>,
#[arg(long)]
dry_run: bool,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
let hours = match hours {
Some(0) => {
console.error("--hours has to be a whole number of at least 1.");
return Ok(1);
}
Some(hours) => hours,
None => config().due.hours.max(1),
};
if !dry_run && !manager.enabled() {
console.warn(DISABLED);
console.line(DISABLED_HINT);
return Ok(0);
}
let now = laravel::now().timestamp();
let since = now.checked_sub((hours as i64).hours())?;
let mut failed = false;
let mut pages: BTreeMap<String, Page> = BTreeMap::new();
for source in manager.sources() {
match source.changed_since(since).await {
Ok(found) => {
for page in found {
let url = page.url.trim().to_owned();
if url.is_empty() || page.changed_at > now {
continue;
}
if pages
.get(&url)
.is_none_or(|existing| page.changed_at > existing.changed_at)
{
pages.insert(url.clone(), Page::new(url, page.changed_at));
}
}
}
Err(error) => {
failed = true;
console.error(format!("{} failed: {error}", source.name()));
}
}
}
detail(console, "Since", &stamp(since));
detail(
console,
if dry_run { "Would submit" } else { "Pages found" },
&pages.len().to_string(),
);
if pages.is_empty() {
console.new_line();
console.info("Nothing to announce.");
return Ok(u8::from(failed));
}
console.new_line();
let mut by_host: BTreeMap<String, Vec<Page>> = BTreeMap::new();
for page in pages.into_values() {
by_host.entry(page.host()).or_default().push(page);
}
if dry_run {
for (host, pages) in &by_host {
detail(
console,
&format!("{host} ({} URLs)", pages.len()),
"<fg=yellow>dry run</>",
);
for page in pages {
console.markup(format!(
" {} <fg=gray>{}</>",
escape_markup(&page.url),
stamp(page.changed_at)
));
}
}
console.new_line();
console.line(" Nothing left the application, this was a dry run.");
console.line(" The deduplication window and the allowed hosts are applied when sending.");
return Ok(u8::from(failed));
}
let total: usize = by_host.values().map(Vec::len).sum();
let mut sent = 0;
for (host, pages) in by_host {
for chunk in pages.chunks(10_000) {
let urls: Vec<String> = chunk.iter().map(|page| page.url.clone()).collect();
match manager.submit_now(urls.clone(), false).await {
Ok(results) => {
for result in &results {
failed = failed || result.failed();
sent += if result.successful { result.count() } else { 0 };
report(console, result);
}
}
Err(error) => {
failed = true;
detail(console, &format!("{host} ({} URLs)", urls.len()), "<fg=red>failed</>");
console.line(format!(" {error}"));
}
}
}
}
if sent < total {
console.new_line();
console.line(format!(
" {sent} of {total} URL(s) were accepted. The rest were held back by the deduplication window, belong to a host with no key, or failed."
));
}
Ok(u8::from(failed))
}
fn stamp(timestamp: Timestamp) -> String {
timestamp.strftime("%Y-%m-%d %H:%M:%S UTC").to_string()
}
#[command("indexnow:flush")]
pub async fn flush(
#[arg(long)]
queue: bool,
console: &mut Console,
manager: Inject<IndexNow>,
) -> laravel::Result<u8> {
if manager.buffered().await? == 0 {
console.info("The buffer is empty.");
return Ok(0);
}
if queue {
console.info(format!("Queued {} URL(s).", manager.flush().await?));
return Ok(0);
}
match manager.flush_now().await {
Ok(results) => {
for result in &results {
report(console, result);
}
Ok(0)
}
Err(error) => failure(console, &error),
}
}
#[command("indexnow:models")]
pub async fn models(console: &mut Console, manager: Inject<IndexNow>) -> laravel::Result<u8> {
let tracked = manager.registry().tracked();
if tracked.is_empty() {
console.warn("No models are tracked.");
console.new_line();
console.line(" Register them in src/app.rs:");
console.new_line();
console.line(" IndexNowServiceProvider::new().track(");
console.line(" indexnow::track::<Post>()");
console.line(" .url_template(\"https://example.com/blog/{slug}\")");
console.line(" .when_holds(\"status\", \"published\"),");
console.line(" )");
console.new_line();
return Ok(0);
}
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
for registration in tracked {
*counts.entry(registration.model_name()).or_default() += 1;
}
let mut seen: BTreeMap<&str, usize> = BTreeMap::new();
let rows: Vec<[String; 2]> = tracked
.iter()
.map(|registration| {
let name = registration.model_name();
let index = seen.entry(name).or_default();
*index += 1;
let label = if counts[name] > 1 {
format!("{name} #{index}")
} else {
name.to_owned()
};
[label, registration.describe()]
})
.collect();
console.table(["Model", "Configured by"], rows.iter().map(|row| [&row[0], &row[1]]));
console.line(" Remember that model events do not fire for query builder writes:");
console.line(" a mass update or delete is invisible here. Use indexnow:sync for those.");
console.new_line();
Ok(0)
}