Custom crawl queue | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  Custom crawl queue

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Custom crawl queue    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Custom crawl queue
==================

###  On this page 

1. [ URL identity ](#content-url-identity)
2. [ Required operations ](#content-required-operations)
3. [ Implementing an adapter ](#content-implementing-an-adapter)
4. [ Durability and cancellation ](#content-durability-and-cancellation)
5. [ Testing a store ](#content-testing-a-store)

Rust's `CrawlStore` owns the frontier, deduplication set, terminal outcomes, and cumulative budgets. `MemoryStore` is the default; `SqliteStore` adds disk-backed checkpoints. A custom store replaces the whole contract, not just a pending-URL queue.

All stores are `Send + Sync`. One store represents one crawl and may have only one active scheduler. `shared_store` allows application code to inspect counts or enqueue roots, not multiple schedulers to process one store concurrently.

URL identity
--------------------------------------------------------------------------------------------

Use `spatie_crawler::url_key` for the built-in identity rules. It removes fragments from an already parsed `url::Url`. URL parsing normalizes host case and default ports. Unlike PHP's queue normalization, trailing slashes and query order remain significant, because servers can assign them different meanings.

Keep the original `CrawlUrl` for fetching and discovery provenance; do not replace it with the deduplication key. Deduplication keeps the first discovery, including parent URL, link text, depth, and resource type. Retain terminal identities so rediscovery does not enqueue them again.

Required operations
-----------------------------------------------------------------------------------------------------------------

Implement every method on `CrawlStore`:

MethodContract`initialize(seed)`Bind the store to a normalized seed identity. Repeating that seed is allowed; a different seed must fail.`enqueue(urls)`Insert new identities as queued, preserving first-discovery payloads and ignoring duplicates in every state.`claim()`Atomically move one queued URL to in-flight and return it, or return `None` when no queued URL exists.`complete(url, outcome, discovered)`Atomically make an in-flight URL terminal and enqueue its new discoveries. Reject completion of an unclaimed or already completed URL.`recover()`Return abandoned in-flight claims to queued state without losing payloads or terminal identities. Safe to repeat under exclusive scheduler ownership.`counts()`Report consistent discovered, queued, in-flight, succeeded, failed, skipped, and mapped totals.`budget()`Return cumulative `attempted` and `elapsed_ms` values.`record_attempt()`Persist one URL-job attempt before its first fetch, not once per retry.`add_elapsed(duration)`Add execution elapsed time to the persisted budget.`Outcome` is `Succeeded`, `Failed`, `Skipped`, or `Mapped`. It lives in `spatie_crawler::store`, along with `StoreCounts` and `StoreBudget`. Counts must track state transitions, not just the number of method calls. `discovered` includes every stored identity, so it equals queued plus in-flight plus all terminal counts.

Implementing an adapter
-----------------------------------------------------------------------------------------------------------------------------

This adapter delegates to the memory store to show all method signatures. Replace the backing operations with your storage engine's atomic operations before relying on it for persistence. Add `async-trait = "0.1"` when implementing the trait in another crate.

```
use async_trait::async_trait;
use spatie_crawler::{CrawlStore, CrawlUrl, Crawler, MemoryStore};
use spatie_crawler::store::{Outcome, StoreBudget, StoreCounts};
use std::time::Duration;

#[derive(Default)]
struct ApplicationStore {
    inner: MemoryStore,
}

#[async_trait]
impl CrawlStore for ApplicationStore {
    async fn initialize(&self, seed: &str) -> spatie_crawler::Result {
        self.inner.initialize(seed).await
    }

    async fn enqueue(&self, urls: Vec) -> spatie_crawler::Result {
        self.inner.enqueue(urls).await
    }

    async fn claim(&self) -> spatie_crawler::Result {
        self.inner.claim().await
    }

    async fn complete(
        &self,
        url: &CrawlUrl,
        outcome: Outcome,
        discovered: Vec,
    ) -> spatie_crawler::Result {
        self.inner.complete(url, outcome, discovered).await
    }

    async fn recover(&self) -> spatie_crawler::Result {
        self.inner.recover().await
    }

    async fn counts(&self) -> spatie_crawler::Result {
        self.inner.counts().await
    }

    async fn budget(&self) -> spatie_crawler::Result {
        self.inner.budget().await
    }

    async fn record_attempt(&self) -> spatie_crawler::Result {
        self.inner.record_attempt().await
    }

    async fn add_elapsed(&self, elapsed: Duration) -> spatie_crawler::Result {
        self.inner.add_elapsed(elapsed).await
    }
}

fn crawler_with_store() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .store(ApplicationStore::default())
        .build()
}
```

Durability and cancellation
-----------------------------------------------------------------------------------------------------------------------------------------

For a persistent backend, completion and discovery insertion must share one transaction. Otherwise a crash can leave a completed parent with lost children, or children committed without their parent's completion. Claims, deduplication, counts, and budget updates also need atomic backend operations.

Cancellation can drop a store future while backend work is still running. Account for operations that may commit even if their caller no longer receives a result. The SQLite implementation runs blocking work on Tokio's blocking pool and serializes operations through its connection. A custom backend must not let late claim/completion writes race with recovery. Enforce exclusive ownership for the full scheduler lifetime and order recovery after prior writes.

The scheduler calls recovery at startup and during cleanup. Attempts already recorded must survive recovery. Elapsed time is added during cleanup, so an abrupt crash can lose time from the interrupted execution. See [crawling across requests](crawling-across-requests) for leases and budgets.

Store durability does not imply exactly-once output. Completion commits before event emission, and `complete` receives discoveries and an outcome, not the page body. A custom store cannot archive emitted pages merely by implementing this method. An output protocol that needs atomic result storage must be designed separately.

Testing a store
-----------------------------------------------------------------------------------------------------

Exercise duplicate enqueueing before and after completion, invalid completions, all terminal outcomes, recovery of in-flight claims, accurate counts, and attempt/time budgets. Reopen persistent storage after an interrupted claim and verify it can be claimed again. Verify that a different seed is refused and that your application prevents concurrent schedulers. SQLite rejects a second open, but an already shared store instance does not enforce scheduler ownership. The crate's `tests/storage.rs` applies the shared state-transition contract to both built-in stores.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
