Skip to main content

fastwarc_grpc/
lib.rs

1// Copyright 2026 Kristian Rickert
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! FastWARC-gRPC exposes the [FastWARC](https://docs.rs/fastwarc) WARC parser as a streaming gRPC
16//! service. Clients in any language with gRPC support can send WARC archives (uncompressed, Gzip,
17//! Zstd, or LZ4) and receive parsed headers and streamed payloads. The
18//! service is binary protobuf only, with no JSON transcoding.
19//!
20//! FastWARC-gRPC belongs to the
21//! [ChatNoir Resiliparse toolkit](https://resiliparse.chatnoir.eu/en/stable/index.html). The
22//! `fastwarc` library carries no gRPC dependencies.
23//!
24//! # Running the Server
25//!
26//! Build and run from the repository root. The build requires `protoc` on the PATH.
27//!
28//! ```bash
29//! FASTWARC_GRPC_ADDR="[::]:50061" cargo run --release -p fastwarc-grpc
30//! ```
31//!
32//! `FASTWARC_GRPC_ADDR` defaults to `[::]:50061`. A Unix socket is accepted as `unix:///path.sock`
33//! or as an absolute filesystem path. Existing socket paths prevent startup; remove a stale socket
34//! manually after confirming that no server owns it. Use a directory controlled by the server operator.
35//! The server shuts down gracefully on SIGINT or SIGTERM and removes its own socket if still present.
36//!
37//! At most 32 parsers run concurrently per service instance, shared by both RPCs and local files.
38//! Excess requests fail with `ResourceExhausted`. The binary accepts a positive
39//! `FASTWARC_GRPC_MAX_CONCURRENT_PARSERS` override; embedders can use
40//! [`WarcParser::with_max_concurrent_parsers`](warc_service::WarcParser::with_max_concurrent_parsers).
41//! Keep the limit below the runtime's blocking-thread capacity. Idle uploads hold a slot until they
42//! finish or are cancelled.
43//! Besides [`WarcService`](proto::fastwarc::v1::warc_service_server::WarcService), it serves the
44//! standard `grpc.health.v1.Health` service for load-balancer probes and gRPC server reflection
45//! (v1), so generic tools can discover the API without local proto files:
46//!
47//! ```bash
48//! grpcurl -plaintext localhost:50061 describe fastwarc.v1.WarcService
49//! ```
50//!
51//! # Parsing a Small Archive in One Call
52//!
53//! `ParseArchive` is the unary entry point for single records and archives that fit within the
54//! gRPC message size limits. This server accepts 16 MiB ([`transport::MAX_MESSAGE_SIZE`]). The
55//! client must use compatible encode and decode limits. One request carries the configuration and
56//! complete archive; the response carries the parsed records and errors.
57//!
58//! The request limit only bounds the compressed archive, so the server also budgets the decoded
59//! response at 16 MiB ([`defaults::MAX_UNARY_RESPONSE_SIZE`]): an archive whose collected records
60//! (payload bytes, encoded metadata, errors, and framing) exceed that budget fails with
61//! `ResourceExhausted`. Use the streaming `ParseWarc` RPC for such archives. This limits response
62//! collection, not parser allocations such as records buffered for digest verification.
63//!
64//! ```no_run
65//! use fastwarc_grpc::proto::fastwarc::v1 as pb;
66//! use fastwarc_grpc::proto::fastwarc::v1::warc_service_client::WarcServiceClient;
67//!
68//! #[tokio::main]
69//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
70//! let mut client = WarcServiceClient::new(fastwarc_grpc::transport::connect("http://localhost:50061").await?)
71//!     .max_decoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE)
72//!     .max_encoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE);
73//! let response = client
74//!     .parse_archive(pb::ParseArchiveRequest {
75//!         config: Some(pb::ParseWarcConfig { parse_http: Some(true), ..Default::default() }),
76//!         archive: std::fs::read("warcfile.warc.gz")?.into(),
77//!     })
78//!     .await?
79//!     .into_inner();
80//!
81//! for record in &response.records {
82//!     let metadata = record.metadata.as_ref().expect("record metadata is always set");
83//!     println!(
84//!         "{}: {} payload bytes",
85//!         metadata.record_id.as_deref().unwrap_or("-"),
86//!         record.payload.len()
87//!     );
88//! }
89//! Ok(())
90//! }
91//! ```
92//!
93//! Compression is detected from the archive's magic bytes.
94//!
95//! # Streaming Large Archives
96//!
97//! `ParseWarc` is the bidirectional RPC for archives that do not fit in one request. The client
98//! sends one `config` message first, then any number of `chunk` messages with archive bytes. The
99//! server reads the chunks in order.
100//! Set `archive_path` on the config to have the server open a local file instead of uploading
101//! chunks (requires a server built with `WarcParser::with_local_files`, or
102//! `FASTWARC_GRPC_ALLOW_LOCAL_FILES=1` plus `FASTWARC_GRPC_LOCAL_FILE_ROOT=/dir` for the bundled
103//! binary; otherwise `PermissionDenied`). Requested paths are confined to the configured root
104//! directory; paths that resolve outside it are rejected with `PermissionDenied`.
105//! In local-file mode, chunk contents are ignored, but duplicate configurations and missing
106//! message kinds are still rejected while parsing is active. The response finishes when the
107//! parser stops, even if the client's request stream remains open.
108//!
109//! Each returned record has one `record_start`, zero or more `payload_chunk` messages, and one
110//! `record_end`.
111//!
112//! ```no_run
113//! use fastwarc_grpc::proto::fastwarc::v1 as pb;
114//! use fastwarc_grpc::proto::fastwarc::v1::warc_service_client::WarcServiceClient;
115//! use tokio_stream::wrappers::ReceiverStream;
116//!
117//! #[tokio::main]
118//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
119//! let (tx, rx) = tokio::sync::mpsc::channel(4);
120//! tx.send(pb::ParseWarcRequest {
121//!     kind: Some(pb::parse_warc_request::Kind::Config(pb::ParseWarcConfig {
122//!         parse_http: Some(true),
123//!         verify_digests: true,
124//!         // Batch events to reduce per-event gRPC overhead.
125//!         response_batch_size: 64,
126//!         ..Default::default()
127//!     })),
128//! })
129//! .await?;
130//! tokio::spawn(async move {
131//!     for chunk in std::fs::read("warcfile.warc.gz").expect("readable file").chunks(64 << 10) {
132//!         let request = pb::ParseWarcRequest {
133//!             kind: Some(pb::parse_warc_request::Kind::Chunk(chunk.to_vec().into())),
134//!         };
135//!         if tx.send(request).await.is_err() {
136//!             break; // Server closed the stream.
137//!         }
138//!     }
139//! });
140//!
141//! let mut client = WarcServiceClient::new(fastwarc_grpc::transport::connect("http://localhost:50061").await?)
142//!     .max_decoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE)
143//!     .max_encoding_message_size(fastwarc_grpc::transport::MAX_MESSAGE_SIZE);
144//! let mut stream = client.parse_warc(ReceiverStream::new(rx)).await?.into_inner();
145//! while let Some(response) = stream.message().await? {
146//!     handle_response(response);
147//! }
148//! Ok(())
149//! }
150//!
151//! fn handle_response(response: pb::ParseWarcResponse) {
152//!     match response.kind {
153//!         // Begin one record and inspect its metadata.
154//!         Some(pb::parse_warc_response::Kind::RecordStart(start)) => {
155//!             let metadata = start.metadata.unwrap_or_default();
156//!             println!("record at offset {}", metadata.stream_pos);
157//!         }
158//!         // Consume the next payload segment for the open record.
159//!         Some(pb::parse_warc_response::Kind::PayloadChunk(chunk)) => {
160//!             println!("  {} payload bytes at offset {}", chunk.data.len(), chunk.offset);
161//!         }
162//!         // Finish the open record.
163//!         Some(pb::parse_warc_response::Kind::RecordEnd(end)) => {
164//!             println!("  done, {} bytes total", end.payload_length);
165//!         }
166//!         // Report a record-level parse failure.
167//!         Some(pb::parse_warc_response::Kind::RecordError(error)) => {
168//!             eprintln!("record error (recoverable: {}): {}", error.recoverable, error.message);
169//!         }
170//!         // Flatten an optional transport batch into the same event handler.
171//!         Some(pb::parse_warc_response::Kind::Batch(batch)) => {
172//!             for item in batch.items {
173//!                 handle_response(item);
174//!             }
175//!         }
176//!         None => {}
177//!     }
178//! }
179//! ```
180//!
181//! This example reads the whole file up front for brevity. `examples/parse.rs` streams a file
182//! through a bounded channel.
183//!
184//! # Configuration and Filters
185//!
186//! [`ParseWarcConfig`](proto::fastwarc::v1::ParseWarcConfig) provides these parsing and filtering
187//! options: `parse_http`,
188//! `decode_http_payload`, `verify_digests`, `quirks_mode`, `max_header_len`, `record_types`,
189//! `min_content_length`, `max_content_length`, `stream_detect`, `input_buffer_size`,
190//! `include_payload`, `include_headers`, `response_batch_size`, and `archive_path`.
191//! Records that do not pass the filters are not returned.
192//!
193//! A non-zero `response_batch_size` groups multiple events in one gRPC message. Defaults and hard
194//! limits for these options live in [`defaults`].
195//!
196//! Custom filter functions cannot be sent over gRPC. Use
197//! [`BuiltinFilter`](proto::fastwarc::v1::BuiltinFilter) or filter the returned metadata on the
198//! client.
199//!
200//! # Digest Verification
201//!
202//! With `verify_digests` set, the server skips records with a missing or invalid
203//! `WARC-Block-Digest`.
204//!
205//! # Wire Mapping
206//!
207//! Header names and values use protobuf `bytes`, not strings, and remain in source order so
208//! duplicate fields are preserved. Each header block also carries serialized bytes. Payload chunks
209//! belong to the most recent `record_start`; a `record_end` closes that record before the next one
210//! begins. The default 32 KiB header limit can be raised to 2 MiB.
211//!
212//! # Error Handling
213//!
214//! Record-level problems arrive as `record_error` messages, not gRPC status codes:
215//!
216//! * An HTTP header parse failure on an already-framed record is **recoverable**. The error is
217//!   reported and the stream continues.
218//! * An HTTP payload decoder setup failure (e.g. an unsupported `Content-Encoding` with
219//!   auto-decoding enabled) is **non-recoverable**: decoder setup consumes the record's reader,
220//!   so the stream cannot advance past the record and ends after the error.
221//! * A WARC framing failure (invalid header, truncated stream) is **non-recoverable** and ends
222//!   the response stream.
223//! * A payload read failure after `record_start` was sent is **non-recoverable**. The server
224//!   emits the `record_error` followed by a `record_end` that terminates the aborted record's
225//!   sequence (its `payload_length` counts the bytes streamed before the failure), then ends the
226//!   stream. Transport failures can interrupt this sequence.
227//!
228//! Protocol violations (missing or duplicate `config`, empty request `kind`) fail the RPC with
229//! `InvalidArgument`.
230//!
231//! # Embedding the Server
232//!
233//! The service implementation is the [`warc_service::WarcParser`] struct. It can be mounted in an
234//! existing tonic server alongside other services. `WarcParser::new()` rejects `archive_path`
235//! requests with `PermissionDenied`; construct it with
236//! [`warc_service::WarcParser::with_local_files`] to let clients open files on the server.
237//! Local file access is confined to the root directory passed to `with_local_files`: files are opened
238//! relative to a retained directory handle (only use this when every client
239//! is trusted with read access to everything under the root):
240//!
241//! ```no_run
242//! use fastwarc_grpc::proto::fastwarc::v1::warc_service_server::WarcServiceServer;
243//! use fastwarc_grpc::warc_service::WarcParser;
244//!
245//! #[tokio::main]
246//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
247//! fastwarc_grpc::transport::configure_server(tonic::transport::Server::builder())
248//!     .add_service(fastwarc_grpc::transport::configure_warc_server(WarcServiceServer::new(WarcParser::new())))
249//!     .serve("[::1]:50061".parse()?)
250//!     .await?;
251//! Ok(())
252//! }
253//! ```
254//!
255//! # Clients in Other Languages
256//!
257//! The protobuf contracts live in `proto/` and follow the buf style guide, so stubs can be
258//! generated for any gRPC language with `buf generate` (see `proto/buf.gen.yaml`) or plain
259//! `protoc`. Ad-hoc calls work without any codegen through server reflection:
260//!
261//! ```bash
262//! grpcurl -plaintext \
263//!   -d "{\"config\":{}, \"archive\":\"$(base64 -w0 record.warc)\"}" \
264//!   localhost:50061 fastwarc.v1.WarcService/ParseArchive
265//! ```
266//!
267//! See `README.md` for build, run, and compatibility notes.
268
269#![deny(missing_docs)]
270#![warn(clippy::pedantic)]
271
272pub mod convert;
273pub mod defaults;
274pub mod transport;
275pub mod warc_service;
276
277/// Generated protobuf and gRPC stubs.
278#[allow(missing_docs, clippy::all, clippy::pedantic, clippy::nursery)]
279pub mod proto {
280    /// Encoded descriptor set of the `fastwarc.v1` package, for server
281    /// reflection.
282    pub const FILE_DESCRIPTOR_SET: &[u8] = tonic::include_file_descriptor_set!("descriptor");
283
284    /// Stubs for the `fastwarc.v1` package.
285    pub mod fastwarc {
286        /// Messages and `WarcService` server/client stubs.
287        pub mod v1 {
288            tonic::include_proto!("fastwarc.v1");
289        }
290    }
291}