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 normalization ](#content-url-normalization)
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)

When crawling a site, the crawler stores URLs to be crawled in a queue. By default, this queue is stored in memory using `MemoryStore`. For large sites or resumable crawls, you can use the built-in `SqliteStore` instead.

You can write your own store by implementing `CrawlStore`. A store keeps queued URLs, deduplication keys, terminal outcomes and cumulative limits. Use only one active scheduler per store; see [checkpoint guarantees](crawling-across-requests#checkpoint-guarantees).

URL normalization
-----------------------------------------------------------------------------------------------------------

The built-in stores normalize URLs before using them as deduplication keys. Use `spatie_crawler::url_key` to apply the same rules in a custom store:

- URL parsing normalizes scheme, host case and default ports.
- The key removes URL fragments.
- Trailing slashes, query ordering and empty query strings remain significant.

The original `CrawlUrl` is preserved for requests and events. The first discovery determines parent URL, link text, depth and resource type; with concurrent crawling, this may not be the shortest path to a page. Keep terminal identities too, so rediscovery does not enqueue completed URLs again.

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

The `CrawlStore` trait requires the following methods:

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`, `StoreCounts` and `StoreBudget` live in `spatie_crawler::store`. Outcomes are `Succeeded`, `Failed`, `Skipped` or `Mapped`. Counts describe state: discovered URLs equal queued, in-flight and terminal URLs combined. They are used for [progress reporting](../basic-usage/tracking-progress).

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

This example delegates to `MemoryStore`. Replace those calls with your own storage operations to persist the queue. Add `async-trait = "0.1"` to your dependencies:

```
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
-----------------------------------------------------------------------------------------------------------------------------------------

Completion and discovery insertion must share one transaction, so a crash cannot save the parent without its children. Claims, deduplication, counts and budget updates also need atomic operations.

Cancellation can drop a store future while backend work is still running. Prevent late writes from racing with recovery: keep exclusive scheduler ownership and finish prior writes before recovery runs. The built-in SQLite store serializes blocking work through its connection.

Recovery runs at startup and during cleanup. Preserve recorded attempts and terminal URLs. Follow the [checkpoint guarantees](crawling-across-requests#checkpoint-guarantees) for recovery, elapsed-time accounting and output delivery. `complete` receives discoveries and an outcome, not the page body.

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

Test duplicate URLs, invalid completions, all terminal outcomes, recovery, counts and cumulative limits. Reopen persistent storage after an interrupted claim and check that it can be claimed again. Reject different seeds and prevent concurrent schedulers. The repository's `tests/storage.rs` exercises these operations on 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)
