laraindexnow 0.1.2

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
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.";

/// A label, then a status, the way Laravel's console components lay out a detail.
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));
}

/// Generate an IndexNow key and show where it has to be published.
#[command("indexnow:key")]
pub async fn key(
    /// The host this key is for, when you serve several domains.
    #[arg(long)]
    host: Option<String>,
    /// Key length, between 8 and 128.
    #[arg(long, default_value_t = 32)]
    length: usize,
    /// Also write `public/<key>.txt`, served without booting the framework.
    #[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(())
}

/// Text files of `public/` named like a key that contain exactly that key, other than `current`.
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
}

/// Check that the IndexNow key file is publicly readable.
#[command("indexnow:verify")]
pub async fn verify(
    /// Check only this host.
    #[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
}

/// Submit URLs to IndexNow.
#[command("indexnow:submit")]
pub async fn submit(
    /// One or more absolute URLs.
    #[arg(required = true)]
    url: Vec<String>,
    /// Buffer and let the queue send it instead of sending now.
    #[arg(long)]
    queue: bool,
    /// Ignore the deduplication window.
    #[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())),
    }
}

/// Submit every indexable record of a tracked model.
#[command("indexnow:sync")]
pub async fn sync(
    /// The tracked model, by short name or full type name.
    model: String,
    /// Rows read per query.
    #[arg(long, default_value_t = 500)]
    chunk: u64,
    /// URLs collected before each submission.
    #[arg(long, default_value_t = 1000)]
    batch: usize,
    /// Stop after this many rows.
    #[arg(long)]
    limit: Option<u64>,
    /// Buffer and let the queue send it instead of sending now.
    #[arg(long)]
    queue: bool,
    /// Ignore the deduplication window.
    #[arg(long)]
    force: bool,
    /// List what would be submitted and send nothing.
    #[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)
    }
}

/// Submit the pages that became public or changed without a write the observers could see.
#[command("indexnow:due")]
pub async fn due(
    /// How many hours to look back, instead of the configured due.hours.
    #[arg(long)]
    hours: Option<u64>,
    /// List what would be submitted and send nothing.
    #[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),
    };

    // Not a failure: a staging machine running this on a schedule is expected, and it must not
    // report an error every day.
    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();

                    // The contract forbids it, but a source is application code.
                    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()
}

/// Send whatever is waiting in the IndexNow buffer.
#[command("indexnow:flush")]
pub async fn flush(
    /// Hand the buffer to the queue instead of sending now.
    #[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),
    }
}

/// List the models tracked by IndexNow.
#[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);
    }

    // A model with several registrations gets one row each: they are an OR, and each has its own
    // conditions worth reading apart.
    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)
}