
# IndexNow for Laravel Rust
<p align="center">
<a href="https://github.com/edulazaro/laraindexnow-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laraindexnow-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laraindexnow"><img src="https://img.shields.io/crates/v/laraindexnow" alt="Crates.io"></a>
<a href="https://crates.io/crates/laraindexnow"><img src="https://img.shields.io/crates/d/laraindexnow" alt="Downloads"></a>
<a href="https://docs.rs/laraindexnow"><img src="https://img.shields.io/docsrs/laraindexnow" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laraindexnow-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laraindexnow" alt="License"></a>
</p>
Tell search engines a URL changed, the moment it changes.
IndexNow is a small protocol: you publish a key file on your domain, then POST the URLs
that changed. Bing, Yandex, Seznam, Naver and Yep consume it, and one submission to the shared
endpoint reaches all of them. **Google does not participate**, so this complements your
sitemap, it does not replace it.
This crate wires the protocol into your models, so publishing a post submits its URL and
unpublishing it submits the URL again, which is the part most implementations miss.
```rust
IndexNowServiceProvider::new().track(
indexnow::track::<Post>()
.url_template("https://example.com/blog/{slug}")
.when_holds("status", "published"),
)
```
That is the whole integration. Nothing is added to the model.
It is the port of [LaraIndexNow](https://github.com/edulazaro/laraindexnow), the PHP package, to
[Laravel Rust](https://laravel.com/rust). **It targets Laravel Rust 0.1, which is in beta, and its
API follows the framework's changes until 1.0.** The behaviour, the names and this document follow
the PHP package. Where Laravel Rust has no equivalent, the section says so, and the
[differences](#differences-from-the-php-package) are collected at the end.
## Installation
```bash
cargo add laraindexnow
```
Register the service provider in `src/app.rs`, with the models you track:
```rust
use laraindexnow as indexnow;
use laraindexnow::IndexNowServiceProvider;
use laravel::Application;
use crate::models::Post;
pub fn configure() -> ApplicationBuilder {
Application::configure().with_providers(|providers| {
providers.add(
IndexNowServiceProvider::new().track(
indexnow::track::<Post>()
.url_template("https://example.com/blog/{slug}")
.when_holds("status", "published"),
),
);
})
}
```
The crate is imported as `laraindexnow`; add `use laraindexnow as indexnow;` if you like the
shorter name used in this document.
The provider adds the configuration, the `IndexNow` service, the key file route, the commands, the
queue jobs and the model observers. It needs the `database` feature of Laravel Rust, which your
application already has if it has models.
Laravel Rust 0.1 does not compile its `database` feature without a backend, so this crate cannot be
built on its own. The `sqlite` feature exists only for that case (docs.rs, a plain `cargo check` of
the crate) and an application never needs it.
## Getting the key in place
Generate a key:
```bash
cargo run -- indexnow:key
```
The command prints the line to add to your configuration, in `src/app.rs`:
```rust
for the days that are not ordinary: a file in `public/` is served before the framework answers
anything else, so it survives a deploy that is half done. Commit it, or generate it again on the
server after deploying. The command warns you about a key file left over from a previous key,
which stays claimable until you delete it.
When the host already has a key, the command asks before replacing it. Without a terminal to ask
in, as in a deploy script, it keeps the configured key and says so, and `--file` writes the file for
that configured key. So the same line works on every deploy:
```bash
cargo run -- indexnow:key --file
```
The address it prints uses the scheme and port of `APP_URL`, so a local `http://localhost:8000`
is not reported as `https`.
Confirm it works before you rely on it:
```bash
cargo run -- indexnow:verify
```
An unreachable key file is the reason behind almost every `403` from the endpoint, and the
endpoint itself tells you nothing useful about which half failed. In production Laravel Rust only
answers requests for the host in `APP_URL` and its subdomains, so an application serving other
domains has to add them to its [trusted hosts](https://laravel.com/rust/docs/0.x/middleware#trusting-hosts).
The key file response goes through the `web` middleware group like any other route, so it carries
the session cookies the group sets. Search engines do not care.
## Tracking models
Register your models in the provider. Each call to `track()` builds a `Registration`:
```rust
IndexNowServiceProvider::new().track(
indexnow::track::<Post>()
.url_template("https://example.com/blog/{slug}")
.when_holds("status", "published")
.ignoring(["views", "last_viewed_at"])
.affects_urls(["https://example.com/blog"]),
)
```
| `url(\|record\| ...)` | | The canonical URL of the record, read from its state. Return `None` and it is never submitted. |
| `url_template("https://example.com/{id}/{slug}")` | | The same, as a template filled from the record's columns. |
| `url_for_model(\|post\| ...)` | | The same, from the typed model. It sees the state after the write only. |
| `previous_url(\|record\| ...)` | | The address a record had before a write, for `url_for_model` registrations. |
| `when("attr")` | the record now | The attribute holds something true. |
| `when_holds("attr", value)` | the record now | The value an attribute has to hold. |
| `when_in("attr", [...])` | the record now | Any of several values. |
| `when_compare("attr", Op::Gte, value)` | the record now | Compared: `Eq`, `Ne`, `Gt`, `Gte`, `Lt`, `Lte`. |
| `when_not("attr")` | the record now | The attribute holds something false. |
| `when_not_holds("attr", value)` | the record now | Anything but that value. |
| `when_all([("a", x), ("b", y)])` | the record now | Several attributes at once. |
| `when_fn(\|record\| ...)` | the record now | A closure judges the whole record. |
| `when_was("attr", value)` | the change | The value the attribute held before this write. |
| `when_was_in("attr", [...])` | the change | Any of several previous values. |
| `when_changed(&["a", "b"])` | the change | Those attributes changed, whatever their values. |
| `when_became("attr", value)` | the change | It just took that value, having held something else. |
| `when_became_in("attr", [...])` | the change | It just took any of several values. |
| `when_became_from("attr", to, from)` | the change | The exact transition, both ends pinned down. |
| `when_left("attr", value)` | the change | It stopped holding that value. |
| `when_left_in("attr", [...])` | the change | It stopped holding any of several values. |
| `when_increments("attr")` | the change | A numeric attribute went up, whatever the amount. |
| `sets("attr")` | | Written on the record once its URL has been handed over. |
| `sets_value("attr", value)`, `sets_with("attr", \|post\| ...)` | | The same, with another value. |
| `ignoring([...])` | | Attributes whose change is not a content change. |
| `affects(\|post\| vec![...])`, `affects_urls([...])` | | Other URLs this write left out of date. |
| `publishes_at("col")`, `changes_at("col")` | | Make the registration a source for `indexnow:due`. |
| `policy(Policy)` | | Rules in a type of their own. |
Attributes are named by column. Laravel Rust models are typed structs, so a condition cannot read a
field by name, and the registration reads every column through the model's metadata instead. That
is what makes `when_was`, `when_became` and the others possible: they need the state the record
held *before* the write, and Laravel Rust hands that over as a list of changed columns, not as a
model. Closures that judge a record, `url` and the policy's `when` therefore receive a `Record`,
which reads columns by name (`record.text("status")`, `record.int("comment_count")`,
`record.bool("published")`), and the same closure runs on both states. The typed model is passed to
`url_for_model`, `affects` and `sets_with`, which only ever need the state after the write.
**Conditions combine with AND, values with OR.** Every condition you chain has to hold. Use the
`_in` variants for several possible values of one attribute, and `when_all` to declare several
conditions at once:
```rust
.when_in("status", ["published", "featured"]) // one attribute, several values
.when_all([("status", "published"), ("review", "correct")]) // several attributes
```
```rust
indexnow::track::<Post>()
.url_template("https://example.com/blog/{slug}")
.when_became("published", true) // it just flipped to true
.when_holds("review", "correct"); // and this holds right now
```
### Reading an attribute as a flag
Named on its own, an attribute has to hold something true, and `when_not()` is the opposite. Truth
is read the way PHP reads it, so `1`, `"1"` and `true` all pass while `0`, `"0"`, `null` and `""`
do not. That covers a column stored as an integer, and it covers a counter: `when("comment_count")`
is "has at least one".
```rust
.when("published") // published is true
.when_not("spam") // spam is false
.when("comment_count") // has at least one
.when_compare("comment_count", Op::Gte, 5_i64)
```
These ask about the record as it stands, so `indexnow:sync` can answer them too and a registration
built only from them is not a transition rule.
### Submitting once, and remembering it
`sets()` writes an attribute on the record once its URL has been handed over. The value defaults to
true, which is the flag column case; `sets_value()` takes another one and `sets_with()` a closure.
Put the same attribute in the conditions and the record drops out the moment it is marked, which is
how you say "submit this once, ever":
```rust
indexnow::track::<Game>()
.url_template("https://example.com/games/{slug}")
.when_not("index_now_sent")
.when("published")
.sets("index_now_sent")
```
It also makes `indexnow:sync` resumable: each pass only picks up what is left, instead of
resubmitting the whole table. A dry run never writes.
Two things to know. The write is quiet (`update_values` on a query, which runs no hooks and fires no
model events), because a normal update would fire another event and the record, having just left
the conditions, would be submitted a second time. And marking means handed over, not accepted by a
search engine: the buffer carries URLs and nothing else, so by the time a submission succeeds or
fails there is no record left to point back at. Listen for `SubmissionFailed` if a failure has to
undo it. Because the write goes straight to the table, it also bumps `updated_at`.
A flag like this is the wrong tool when a page should be resubmitted after an edit, since a written
record never comes back. For that, declare the edit as its own registration with `when_changed()`.
### Several ways in: registrations combine with OR
Conditions on one registration are an AND, and sometimes that is not the shape of the problem. A
record can become worth indexing through more than one route, each with conditions of its own, and
no single AND describes all of them at once.
Track the same model again and you get a second registration. Registrations are an **OR**: a write
is submitted when any of them wants it.
```rust
// A game page is worth indexing once it is approved and has playthroughs.
// Either half can be the one that arrives last, so declare both routes.
IndexNowServiceProvider::new()
.track(
indexnow::track::<Game>()
.url_template("https://example.com/games/{slug}")
.when_left("playthroughs", 0_i64) // playthroughs arrived, already approved
.when_holds("approved", true),
)
.track(
indexnow::track::<Game>()
.url_template("https://example.com/games/{slug}")
.when_became("approved", true) // approval arrived, playthroughs already there
.when_fn(|game| game.int("playthroughs").unwrap_or(0) > 0),
)
```
Writing that as one registration does not work: `when_left(...)` and `when_became(...)` on the same
chain would demand both transitions in the same write, which never happens.
Each registration keeps its own `url`, `ignoring`, `affects` and policy, so they are read and
reasoned about separately. The model is observed once however many registrations it has, and a URL
that two of them resolve is submitted once.
### Naming the URL
Laravel Rust 0.1 has no named routes, so there is no `route('blog.show', $post)`. A registration
names its URL in one of three ways:
```rust
.url_template("https://example.com/blog/{slug}") // filled from the record's columns
.url(|post| Some(format!("https://example.com/blog/{}", post.text("slug")?)))
.url_for_model(|post: &Post| Some(format!("https://example.com/blog/{}", post.slug)))
```
A template is percent encoded, and gives no URL when a placeholder names an empty column. The first
two read a `Record`, so they also resolve the address the record had before a write, which is how a
changed slug announces the old URL as well as the new one. `url_for_model` reads the typed model,
which is nicer to write and only knows the state after the write: pair it with `previous_url` if
the old address matters.
`affects_urls()` takes a fixed list and `affects()` a closure over the model:
```rust
.affects_urls(["https://example.com/blog", "https://example.com/novedades"])
.affects(|post: &Post| vec![format!("https://example.com/blog/category/{}", post.category_id)])
```
### Policy classes
When the rules grow, or you want them testable on their own, implement `Policy`:
```rust
use laraindexnow::{Policy, Record};
struct PostIndexNow;
impl Policy<Post> for PostIndexNow {
fn url(&self, post: &Post) -> Option<String> {
Some(format!("https://example.com/blog/{}", post.slug))
}
fn when(&self, record: &Record) -> bool {
record.text("status") == Some("published")
}
}
```
```rust
IndexNowServiceProvider::new().track(indexnow::track::<Post>().policy(PostIndexNow))
```
Only `url()` is required. `previous_url()`, `ignoring()` and `affects()` are optional, and the
registration's own `url` and `affects` win over the policy's.
A registration with neither a URL resolver nor a policy stops the application from booting, and so
does a `changes_at()` without `publishes_at()`, because that registration could never be a source.
Catching it when the application starts beats finding out from a submission that never went out.
## What actually triggers a submission
**With a transition condition**, that condition decides, full stop. `when_became`,
`when_became_from`, `when_left`, `when_increments`, `when_changed` and `when_was` all need both
states, so they only apply to writes.
`when_increments` cares about direction, not amount: a counter going from 3 to 4 matches like one
going from 0 to 90. To catch only the first rise, which is the usual "this page now has enough
content to be worth indexing" case, reach for `when_left("attr", 0_i64)` instead.
**Without one**, the default rule applies, and it asks a single question: does this record belong
in the index, before and after? That answer is whatever your `when` conditions return, as a plain
true or false.
**With `publishes_at()`**, the date is part of that answer in both cases: a record with no date, or
with a date still ahead, is not in the index yet. Saving a scheduled post submits nothing, and
`indexnow:sync` does not list it. `indexnow:due` announces it when the date comes, and moving the
date into the past by hand counts as entering the index.
| false | false | no |
| false | true | yes, it entered the index |
| true | true | only if a content attribute changed |
| true | false | **yes**, it left the index |
That last row is the one most implementations get wrong. A record leaving the index matters as much
as one entering it: the URL now 404s and the engines should be told to look. The same goes for a
deleted record, and for a changed slug, where both the old and the new URL go out.
Three model events are observed: `Created`, `Updated` and `Deleted`. Laravel Rust 0.1 has no soft
deletes and no `Restored` event. A model that hides rows with a `deleted_at` column leaves the
index through an ordinary update, so `when_not("deleted_at")` covers it, and bringing it back is an
update that enters the index again. An update that changes nothing fires no event and submits
nothing.
Laravel Rust dispatches model events after the surrounding transaction commits, and discards them if
it rolls back, so a rolled back write never reaches a search engine. There is nothing to configure.
An error while announcing a write is reported and never returned: announcing a URL is never worth
losing the write it was announcing.
### The gap you need to know about
**Model events do not fire for query builder writes.** This publishes a hundred posts and IndexNow
hears about none of them:
```rust
Post::query()
.filter(Post::status.eq("draft"))
.update_values(values! { status: "published" })
.await?;
```
The same is true of `delete()` on a query, `insert()` and `upsert()`. No package can intercept
those. That is what `indexnow:sync` is for:
```bash
cargo run -- indexnow:sync post
```
It walks the table, evaluates the same `when` conditions the observer uses, and submits everything
that qualifies. Use `--dry-run` first. The model is named by its struct (`post`, case insensitive)
or by its full type name.
## Content that changes without a write
Submissions come from model events, and two kinds of content never produce one:
- **Scheduled content.** A post dated for Friday goes live on Friday because the clock moves, not
because anything writes to the row. No event fires, so nothing is announced.
- **Content that is not in a model.** Markdown posts, or any page that is only listed in a sitemap.
`indexnow:due` covers both. It asks a set of *sources* which pages became public or changed in the
last few hours and submits them. It runs on the schedule you give it, so nothing has to happen at
the moment the content changes.
### Scheduled models
Tell the registration which column holds the moment the record goes public, and optionally which
one holds the last content change:
```rust
indexnow::track::<Post>()
.url_template("https://example.com/blog/{slug}")
.when_holds("status", "published")
.publishes_at("published_at")
.changes_at("content_updated_at")
.affects_urls(["https://example.com/blog"])
```
A registration with `publishes_at()` is still an observer, exactly as before, and now it is a source
as well. It finds the rows whose publish date or change date falls inside the window and is not in
the future, so a scheduled row is only returned once its date has passed. Each page is dated with
the later of the two dates that fall inside the window.
Everything else about the registration applies. Its `when` conditions are evaluated for each
record, the same way the observer and `indexnow:sync` evaluate them, so a draft whose date passed is
not announced. The URL resolver gives the address, and the `affects` URLs are returned too. Only
conditions about the record as it stands take part, as in `indexnow:sync`: a transition such as
`when_became()` needs a write to compare against, and there is none here. `sets()` is not applied.
`changes_at()` needs `publishes_at()`. Without a change column, only the publish date counts, and an
edit made through the query builder is not announced.
### Sitemaps and your own sources
**There is no Larablog source yet.** The PHP package's `sources.larablog` setting, its `noindex`
front matter and its `larablogUrls()` resolver have no counterpart here. Markdown posts go through a
sitemap, or through a source of your own.
**A sitemap.** Any list of URLs with a modification date:
```rust
IndexNowServiceProvider::new().sitemap("https://example.com/sitemap.xml")
```
or in the configuration, where it needs no code:
```rust
config.section_mut::<IndexNowConfig>().sources.sitemaps.push("https://example.com/sitemap.xml".into());
```
It fetches the file with Laravel Rust's HTTP client and follows sitemap index files, up to three
levels deep and never the same file twice. A `.xml.gz` sitemap is read as it is stored. A URL is
returned when its `<lastmod>` falls inside the window. A `<lastmod>` is an RFC 3339 date and time,
or a bare date, which means midnight UTC, and one with no offset is read as UTC. **URLs without a
`<lastmod>` are ignored**: the sitemap does not say when they changed, and treating them as changed
would announce the whole site on every run. A sitemap that cannot be fetched or read is reported and
makes the command exit with an error, rather than passing for a quiet day.
**Your own.** Implement `Source` and register it:
```rust
use async_trait::async_trait;
use laraindexnow::{Page, Source};
use laravel::time::Timestamp;
struct DocsSource;
#[async_trait]
impl Source for DocsSource {
async fn changed_since(&self, since: Timestamp) -> laravel::Result<Vec<Page>> {
Ok(Docs::updated_since(since)
.await?
.into_iter()
.map(|doc| Page::new(doc.url(), doc.updated_at))
.collect())
}
}
IndexNowServiceProvider::new().source(DocsSource)
```
A source returns the pages that became public or changed between `since` and now, each with an
absolute URL and the date of the change. Never return a date in the future. `indexnow::source()`
and `indexnow::sitemap()` register one while the application runs, and `indexnow::sources()` lists
what `indexnow:due` reads.
### Running it
```bash
cargo run -- indexnow:due # the last 25 hours
cargo run -- indexnow:due --hours=2 # the last 2 hours
cargo run -- indexnow:due --dry-run # list what it would send, send nothing
```
The crate does not schedule it for you. Add it where you schedule everything else, in
`src/console/mod.rs`:
```rust
#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
schedule.command("indexnow:due").daily_at("00:05").without_overlapping();
}
```
The command has no memory. On every run it collects what became public or changed in the last
`--hours` hours, up to now and never in the future, and submits it through the same path as
`indexnow:submit`: batching per host, the environment guard, the transport, logging, events and the
deduplication window all apply. It records nothing.
Make the window a little longer than the interval you schedule it at, so a late run leaves no gap.
The default of 25 hours matches a daily schedule; run it hourly with `--hours=2`. Submitting a URL
twice does no harm. **The trade-off is that a run missed for longer than the window is never made
up for**: the pages of that stretch are not announced unless you run the command by hand with a
larger `--hours`.
Outside the configured environments the command does nothing and exits successfully, so the same
schedule can run everywhere. It exits with an error when a submission failed or a source could not
be read.
A URL the observers already announced, and that a source also reports, is sent again by
`indexnow:due`. The deduplication window absorbs it when it is recent enough.
## Submitting by hand
```rust
indexnow::submit("https://example.com/page").await?; // buffered, sent by the queue
indexnow::submit(["https://example.com/a", "https://example.com/b"]).await?;
indexnow::submit_now(url).await?; // sent inline, returns the results
indexnow::submit_model(&post).await?; // resolves the URL from the registration
```
`submit` and `submit_now` take one URL or any list of them. They are free functions that resolve the
`IndexNow` service; a handler or a command can take an `Inject<IndexNow>` instead and call the same
methods (`submit_now` there also takes a `force` flag that ignores the deduplication window).
And when you are importing, seeding or backfilling:
```rust
indexnow::without_submissions(async {
for post in posts {
create!(Post { slug: &post.slug, title: &post.title }).await?;
}
Ok::<_, laravel::Error>(())
})
.await?;
```
Model events fired inside are observed and discarded. Work you spawn with `tokio::spawn` is not
covered; spawn it with `laravel::task::spawn` inside the block.
## Buffering, queueing and deduplication
Model events do not send HTTP requests. They push URLs into a cache backed buffer and schedule one
delayed job to drain it, so saving a hundred rows produces one request rather than a hundred.
Exactly one flush job exists per window, no matter how many events arrive.
The same URL is not submitted twice within the deduplication window. Editing a post five times in
ten minutes is one submission. **Keep that window short** (the default is an hour). It is an
anti-bounce measure, not a record of what is already indexed, and a long window swallows real
edits: publish at 09:00 with a 24 hour window and the correction you make at 15:00 never goes out.
Retries live on the job, not on the transport. A `429` is released with the endpoint's own
`Retry-After`; a `5xx` or a connection failure fails the attempt and the job backs off at 1, 5 and
15 minutes, four attempts in all. A rejected key or a malformed URL (`400`, `403`, `422`) is never
retried, because retrying will not fix it. The last attempt fails with the reason the submission
actually failed for, which is what lands in the failed jobs table.
With `queue.enabled` off, everything is sent inline instead. Both the buffer and the deduplication
window live in the cache store named by `buffer.store`, or in the default one, so use a shared store
such as `redis` or `database` when you run several servers.
Laravel Rust sends every job to the `sync` connection in tests, so a buffered submission is sent as
soon as its delayed flush is dispatched there. Fake the queue (`queue::fake()`) to look at the jobs
instead.
## Several domains from one application
Map a key per host:
```rust
let indexnow = config.section_mut::<IndexNowConfig>();
indexnow.keys.insert("example.com".into(), "ecd5c0c8f2ad4b0e9a0d1f2c3b4a5968".into());
indexnow.keys.insert("example.org".into(), "5f3a9d7e1b2c4a6d8e0f1a2b3c4d5e6f".into());
```
The key file route answers with the right key for whichever host was requested, submissions are
grouped per host before being sent, and URLs whose host is not configured are dropped rather than
submitted against the wrong key. `indexnow:verify` checks every host at once.
## Commands
Run them with your application's binary, as in `cargo run -- indexnow:key`.
| `indexnow:key` | Generate a key and show where it has to be published |
| `indexnow:verify` | Check the key file is publicly readable and correct |
| `indexnow:submit {url*}` | Submit URLs by hand, inline by default |
| `indexnow:sync {model}` | Submit every indexable record of a tracked model |
| `indexnow:due {--hours=} {--dry-run}` | Submit what became public or changed in the last hours without a write: scheduled models, sitemaps, your own sources |
| `indexnow:flush` | Send whatever is waiting in the buffer |
| `indexnow:models` | List the tracked models |
Commands send inline by default, because when you run one you want the status code on screen, not a
queued job. Pass `--queue` for the opposite.
Options: `indexnow:key` takes `--host`, `--length` and `--file`; `indexnow:verify` takes `--host`;
`indexnow:submit` takes `--queue` and `--force`; `indexnow:sync` takes `--chunk`, `--batch`,
`--limit`, `--queue`, `--force` and `--dry-run`; `indexnow:flush` takes `--queue`.
## Testing
```rust
let fake = indexnow::fake().await?;
create!(Post { slug: "hello", title: "Hello", status: "published" }).await?;
fake.assert_submitted("https://example.com/blog/hello");
fake.assert_submitted_count(2);
fake.assert_nothing_submitted();
```
`fake()` swaps the transport and bypasses the queue, so assertions work without a worker. The fake
also has `assert_not_submitted`, `assert_submitted_where`, `submissions()`, `submitted()` and
`reset()`.
It does not lift the environment guard, though: submissions only happen in the environments listed
in `environments`, `production` by default, and that includes faked ones. In the `testing`
environment nothing is recorded and every assertion fails, so allow it in your test application:
```rust
| `enabled` | `true` | Master switch, the only setting reading the environment (`INDEXNOW_ENABLED`) |
| `environments` | `["production"]` | Where submissions may happen. Empty means everywhere |
| `endpoint` | `https://api.indexnow.org/indexnow` | The shared endpoint |
| `timeout` | `10` | Seconds to wait for the endpoint |
| `driver` | `Driver::Http` | `Http` or `Null` |
| `key` / `keys` | `None` / `{}` | Single key, or one per host |
| `key_location` | `None` | Only when the key file is hosted outside the root of the domain |
| `serve_key_file` | `true` | Serve `/{key}.txt` from the application |
| `hosts` | `[]` | Allowed hosts, derived from the keys (or from `APP_URL`) when empty |
| `queue.enabled` | `true` | Buffer and queue, or send inline |
| `queue.connection`, `queue.queue` | `None` | Where the jobs go |
| `buffer.store` | `None` | The cache store, or the default one |
| `buffer.key` | `indexnow:buffer` | The cache key of the buffer |
| `buffer.delay` | `60` | Seconds before the buffer is drained |
| `buffer.max_urls` | `10000` | The buffer flushes early when it holds this many URLs |
| `dedupe.enabled`, `dedupe.ttl`, `dedupe.prefix` | `true`, `3600`, `indexnow:sent:` | The deduplication window, in seconds |
| `ignored_attributes` | `remember_token`, `views`, `view_count`, `last_seen_at` | Changes limited to these are not a content change |
| `log` | `LogMode::Null` | `Null` or `Log` (written through `tracing`) |
| `due.hours` | `25` | Hours `indexnow:due` looks back, overridden by `--hours` |
| `sources.models` | `true` | Read the models tracked with `publishes_at` in `indexnow:due` |
| `sources.sitemaps` | `[]` | Sitemaps `indexnow:due` reads |
The timestamp columns of each model are always ignored. The PHP package's `log_channel` and
`table` settings and its `database` log mode do not exist here: `tracing` decides where the log
goes, and there is no migration to publish.
## Events
`UrlsSubmitted` and `SubmissionFailed`, both carrying the `SubmissionResult` with the host, the
URLs, the status code and a message written to be read by a human. `SubmissionFailed` also carries
the error of a failure that will be retried.
```rust
use laraindexnow::SubmissionFailed;
use laravel::event::{Event, listener};
#[listener]
async fn log_the_failure(event: Event<SubmissionFailed>) {
tracing::warn!(host = %event.result.host, "IndexNow failed: {}", event.result.message);
}
```
## Differences from the PHP package
- **Models are typed.** Conditions name columns and read a `Record`, URLs come from a template or a
closure over the record, and the typed model is available where only the state after the write
matters. There are no named routes in Laravel Rust 0.1, so there is no route name as a URL.
- **Registrations go in the provider**, not in a facade call, because the observers are registered
on the event dispatcher while the application is built. `indexnow::track::<Post>()` builds the
registration and `IndexNowServiceProvider::track` takes it.
- **The key is not written for you** (see [the key](#getting-the-key-in-place)).
- **No `restored` event, no Larablog source, no database logger.** Laravel Rust 0.1 has no soft
deletes, the Larablog source is not in the Rust version yet, and the log goes through `tracing`.
- **Submissions are always a `POST` with the JSON body.** The PHP package sends a single URL as a
`GET`. The protocol accepts both and one code path is easier to reason about.
- **The key file is one route per configured key.**
- **`publishes_at()` decides on its own as well.** In the PHP package it only makes the model a
source for `indexnow:due`, so a scheduled post that passes `when` is submitted on save unless a
condition checks the date. Here a date still ahead keeps the record out of the index for the
observer and `indexnow:sync` too.
- **`indexnow:key` without a terminal keeps the configured key** and writes its file with `--file`.
The PHP package stops at the question and writes nothing.
- **The environment guard reads the application's environment name**, `APP_ENV`, as `environments`
lists it.
## Sponsors
IndexNow for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:
<p>
<a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
IndexNow for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).