Skip to main content

Crate fastwarc_grpc

Crate fastwarc_grpc 

Source
Expand description

FastWARC-gRPC exposes the FastWARC WARC parser as a streaming gRPC service. Clients in any language with gRPC support can send WARC archives (uncompressed, Gzip, Zstd, or LZ4) and receive parsed headers and streamed payloads. The service is binary protobuf only, with no JSON transcoding.

FastWARC-gRPC belongs to the ChatNoir Resiliparse toolkit. The fastwarc library carries no gRPC dependencies.

§Running the Server

Build and run from the repository root. The build requires protoc on the PATH.

FASTWARC_GRPC_ADDR="[::]:50061" cargo run --release -p fastwarc-grpc

FASTWARC_GRPC_ADDR defaults to [::]:50061. A Unix socket is accepted as unix:///path.sock or as an absolute filesystem path. Existing socket paths prevent startup; remove a stale socket manually after confirming that no server owns it. Use a directory controlled by the server operator. The server shuts down gracefully on SIGINT or SIGTERM and removes its own socket if still present.

At most 32 parsers run concurrently per service instance, shared by both RPCs and local files. Excess requests fail with ResourceExhausted. The binary accepts a positive FASTWARC_GRPC_MAX_CONCURRENT_PARSERS override; embedders can use WarcParser::with_max_concurrent_parsers. Keep the limit below the runtime’s blocking-thread capacity. Idle uploads hold a slot until they finish or are cancelled. Besides WarcService, it serves the standard grpc.health.v1.Health service for load-balancer probes and gRPC server reflection (v1), so generic tools can discover the API without local proto files:

grpcurl -plaintext localhost:50061 describe fastwarc.v1.WarcService

§Parsing a Small Archive in One Call

ParseArchive is the unary entry point for single records and archives that fit within the gRPC message size limits. This server accepts 16 MiB (transport::MAX_MESSAGE_SIZE). The client must use compatible encode and decode limits. One request carries the configuration and complete archive; the response carries the parsed records and errors.

The request limit only bounds the compressed archive, so the server also budgets the decoded response at 16 MiB (defaults::MAX_UNARY_RESPONSE_SIZE): an archive whose collected records (payload bytes, encoded metadata, errors, and framing) exceed that budget fails with ResourceExhausted. Use the streaming ParseWarc RPC for such archives. This limits response collection, not parser allocations such as records buffered for digest verification.

use fastwarc_grpc::proto::fastwarc::v1 as pb;
use fastwarc_grpc::proto::fastwarc::v1::warc_service_client::WarcServiceClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = WarcServiceClient::new(fastwarc_grpc::transport::connect("http://localhost:50061").await?)
    .max_decoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE)
    .max_encoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE);
let response = client
    .parse_archive(pb::ParseArchiveRequest {
        config: Some(pb::ParseWarcConfig { parse_http: Some(true), ..Default::default() }),
        archive: std::fs::read("warcfile.warc.gz")?.into(),
    })
    .await?
    .into_inner();

for record in &response.records {
    let metadata = record.metadata.as_ref().expect("record metadata is always set");
    println!(
        "{}: {} payload bytes",
        metadata.record_id.as_deref().unwrap_or("-"),
        record.payload.len()
    );
}
Ok(())
}

Compression is detected from the archive’s magic bytes.

§Streaming Large Archives

ParseWarc is the bidirectional RPC for archives that do not fit in one request. The client sends one config message first, then any number of chunk messages with archive bytes. The server reads the chunks in order. Set archive_path on the config to have the server open a local file instead of uploading chunks (requires a server built with WarcParser::with_local_files, or FASTWARC_GRPC_ALLOW_LOCAL_FILES=1 plus FASTWARC_GRPC_LOCAL_FILE_ROOT=/dir for the bundled binary; otherwise PermissionDenied). Requested paths are confined to the configured root directory; paths that resolve outside it are rejected with PermissionDenied. In local-file mode, chunk contents are ignored, but duplicate configurations and missing message kinds are still rejected while parsing is active. The response finishes when the parser stops, even if the client’s request stream remains open.

Each returned record has one record_start, zero or more payload_chunk messages, and one record_end.

use fastwarc_grpc::proto::fastwarc::v1 as pb;
use fastwarc_grpc::proto::fastwarc::v1::warc_service_client::WarcServiceClient;
use tokio_stream::wrappers::ReceiverStream;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (tx, rx) = tokio::sync::mpsc::channel(4);
tx.send(pb::ParseWarcRequest {
    kind: Some(pb::parse_warc_request::Kind::Config(pb::ParseWarcConfig {
        parse_http: Some(true),
        verify_digests: true,
        // Batch events to reduce per-event gRPC overhead.
        response_batch_size: 64,
        ..Default::default()
    })),
})
.await?;
tokio::spawn(async move {
    for chunk in std::fs::read("warcfile.warc.gz").expect("readable file").chunks(64 << 10) {
        let request = pb::ParseWarcRequest {
            kind: Some(pb::parse_warc_request::Kind::Chunk(chunk.to_vec().into())),
        };
        if tx.send(request).await.is_err() {
            break; // Server closed the stream.
        }
    }
});

let mut client = WarcServiceClient::new(fastwarc_grpc::transport::connect("http://localhost:50061").await?)
    .max_decoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE)
    .max_encoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE);
let mut stream = client.parse_warc(ReceiverStream::new(rx)).await?.into_inner();
while let Some(response) = stream.message().await? {
    handle_response(response);
}
Ok(())
}

fn handle_response(response: pb::ParseWarcResponse) {
    match response.kind {
        // Begin one record and inspect its metadata.
        Some(pb::parse_warc_response::Kind::RecordStart(start)) => {
            let metadata = start.metadata.unwrap_or_default();
            println!("record at offset {}", metadata.stream_pos);
        }
        // Consume the next payload segment for the open record.
        Some(pb::parse_warc_response::Kind::PayloadChunk(chunk)) => {
            println!("  {} payload bytes at offset {}", chunk.data.len(), chunk.offset);
        }
        // Finish the open record.
        Some(pb::parse_warc_response::Kind::RecordEnd(end)) => {
            println!("  done, {} bytes total", end.payload_length);
        }
        // Report a record-level parse failure.
        Some(pb::parse_warc_response::Kind::RecordError(error)) => {
            eprintln!("record error (recoverable: {}): {}", error.recoverable, error.message);
        }
        // Flatten an optional transport batch into the same event handler.
        Some(pb::parse_warc_response::Kind::Batch(batch)) => {
            for item in batch.items {
                handle_response(item);
            }
        }
        None => {}
    }
}

This example reads the whole file up front for brevity. examples/parse.rs streams a file through a bounded channel.

§Configuration and Filters

ParseWarcConfig provides these parsing and filtering options: parse_http, decode_http_payload, verify_digests, quirks_mode, max_header_len, record_types, min_content_length, max_content_length, stream_detect, input_buffer_size, include_payload, include_headers, response_batch_size, and archive_path. Records that do not pass the filters are not returned.

A non-zero response_batch_size groups multiple events in one gRPC message. Defaults and hard limits for these options live in defaults.

Custom filter functions cannot be sent over gRPC. Use BuiltinFilter or filter the returned metadata on the client.

§Digest Verification

With verify_digests set, the server skips records with a missing or invalid WARC-Block-Digest.

§Wire Mapping

Header names and values use protobuf bytes, not strings, and remain in source order so duplicate fields are preserved. Each header block also carries serialized bytes. Payload chunks belong to the most recent record_start; a record_end closes that record before the next one begins. The default 32 KiB header limit can be raised to 2 MiB.

§Error Handling

Record-level problems arrive as record_error messages, not gRPC status codes:

  • An HTTP header parse failure on an already-framed record is recoverable. The error is reported and the stream continues.
  • An HTTP payload decoder setup failure (e.g. an unsupported Content-Encoding with auto-decoding enabled) is non-recoverable: decoder setup consumes the record’s reader, so the stream cannot advance past the record and ends after the error.
  • A WARC framing failure (invalid header, truncated stream) is non-recoverable and ends the response stream.
  • A payload read failure after record_start was sent is non-recoverable. The server emits the record_error followed by a record_end that terminates the aborted record’s sequence (its payload_length counts the bytes streamed before the failure), then ends the stream. Transport failures can interrupt this sequence.

Protocol violations (missing or duplicate config, empty request kind) fail the RPC with InvalidArgument.

§Embedding the Server

The service implementation is the warc_service::WarcParser struct. It can be mounted in an existing tonic server alongside other services. WarcParser::new() rejects archive_path requests with PermissionDenied; construct it with warc_service::WarcParser::with_local_files to let clients open files on the server. Local file access is confined to the root directory passed to with_local_files: files are opened relative to a retained directory handle (only use this when every client is trusted with read access to everything under the root):

use fastwarc_grpc::proto::fastwarc::v1::warc_service_server::WarcServiceServer;
use fastwarc_grpc::warc_service::WarcParser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
fastwarc_grpc::transport::configure_server(tonic::transport::Server::builder())
    .add_service(fastwarc_grpc::transport::configure_warc_server(WarcServiceServer::new(WarcParser::new())))
    .serve("[::1]:50061".parse()?)
    .await?;
Ok(())
}

§Clients in Other Languages

The protobuf contracts live in proto/ and follow the buf style guide, so stubs can be generated for any gRPC language with buf generate (see proto/buf.gen.yaml) or plain protoc. Ad-hoc calls work without any codegen through server reflection:

grpcurl -plaintext \
  -d "{\"config\":{}, \"archive\":\"$(base64 -w0 record.warc)\"}" \
  localhost:50061 fastwarc.v1.WarcService/ParseArchive

See README.md for build, run, and compatibility notes.

Modules§

convert
Conversions between fastwarc types and fastwarc.v1 protobuf messages.
defaults
Parser configuration defaults and service limits.
proto
Generated protobuf and gRPC stubs.
transport
Shared HTTP/2 settings for WARC transfer.
warc_service
Streaming and unary RPCs backed by blocking parser tasks. Input chunks pass through channel_reader; parser produces record events, and batch groups them for the streaming response.