unwarc

package module
v0.0.0-...-30ffdd4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: CC0-1.0 Imports: 11 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

unwarc

unwarc is a Go library for reading WARC.

It is aimed at readers, validators, indexers, and extraction pipelines.

Highlights

  • Lazy random access: scan once, keep RecordRefs, and reopen raw records or blocks later.
  • Handles both record-aligned and non-record-aligned compression layouts: one gzip member/zstd frame per record, one compression unit containing many records, or records crossing unit boundaries.
  • Supports the WARC-zstd record-local seek-index profile proposed in warc-specifications#118.
  • Follow WARC terminology.
  • Customizable, Developer-friendly.
  • Block-level APIs: read the full WARC record, just the declared block, or a range inside the block without pretending to understand payload semantics.
  • Small, composable core: no built-in network clients or WARC writer (saveweb/gowarc), whole-file xz/bzip2/LZ4 decoders (github.com/saveweb/decodedsource), validator (TODO), content block parser (TODO), warc rewriter (TODO), CDX indexer&writer&reader (TODO); those belong in adjacent layers.

unwarc Package Terminology

unwarc has a few concepts that come from its scanning model rather than from the WARC specification itself. The short version is:

Source -> Scanner -> RecordReader or finalized RecordRef -> optional lazy reopen
Input and scanning
  • A source is something that can open the input bytes. Source only needs Open; RandomAccessSource can also reopen byte ranges with OpenRange, OpenAt, and Size. NewFileSource is the built-in local-file source.
  • A scanner is the stateful reader created by NewScanner, NewScannerFromSource, or NewScannerAt. It discovers WARC record boundaries in order.
  • NewScanner reads from an io.Reader. It is stream-only: once bytes have passed, old records cannot be reopened.
  • NewScannerFromSource reads from a RandomAccessSource. It can produce references that reopen records later, as long as the backing bytes stay stable.
  • NewScannerAt starts scanning at an encoded byte offset that is already a valid compression-unit boundary: plain WARC record boundary, gzip member boundary, or zstd frame boundary.
Records and references
  • A record reader (RecordReader) is returned by NextRecord. It owns the currently active record and streams the record block once through Block. This is usually the simplest and fastest path for sequential processing.
  • A record reference (RecordRef) is unwarc's durable description of a scanned record. It stores the parsed header, raw header bytes, content length, trailer length, diagnostics, and the information needed to reopen the record later when possible.
  • A reference is finalized when unwarc has consumed enough bytes to know the record's trailer, compression-unit relationship, access mode, and reopen plan. References from Scanner.Next are finalized before they are exposed. References from RecordReader.Ref become finalized only after the block is exhausted or the record is closed.
  • OpenRaw reopens the full decoded WARC record: header, block, and trailer. OpenBlock reopens only the bytes declared by Content-Length. OpenBlockRange reopens a byte range inside that block.
Offsets and access modes
  • Encoded offsets are byte offsets in the stored input file or object. For .warc.gz and .warc.zst, these are compressed offsets. OpenRange, OpenAt, DecodeCost.EncodedRanges, and NewScannerAt use encoded offsets.
  • Decoded offsets are byte offsets in the uncompressed WARC byte stream seen by a scanner. RecordLocation.Uncompressed uses decoded offsets. These are useful for describing record order and decoded layout, but they are not file offsets and must not be passed to NewScannerAt.
  • A compression unit is a storage-layer unit such as a gzip member, zstd frame, zstd dictionary frame, or zstd skippable frame. It is not a WARC segment and is unrelated to WARC-Segment-*.
  • A restart point is the encoded offset where lazy reopening has to start. For record-aligned compression it is the record's own encoded start. For solid or crossed compression units it may be an earlier gzip member or zstd frame, after which unwarc decodes and discards bytes until the requested record or block begins.
  • AccessExact means the encoded ranges map exactly to the requested record. AccessFromCompressionUnitStart means reopening starts at an earlier compression-unit boundary and discards decoded bytes. AccessStreamOnly means the record was found but cannot be reopened later. AccessInvalid means no usable location could be resolved.
Cost, indexes, and diagnostics
  • A decode cost (DecodeCost) describes the work hidden behind lazy reopening: which encoded ranges must be read, how many decoded bytes must be discarded first, and how many decoded bytes will be returned. Use RawDecodeCost, BlockDecodeCost, or BlockRangeDecodeCost before lazy opening when you want to avoid expensive solid-compression reads.
  • A block index (BlockIndex) is optional frame-level mapping for formats that carry recognized per-record block indexes. When present, OpenBlockRange can reopen only the compressed frames overlapping the requested block range.
  • Issues are non-fatal diagnostics attached to a finalized RecordRef, such as a missing record trailer, a solid gzip member, or a zstd frame shared by multiple WARC records. DefaultScannerOptions turns the common recoverable validation issues into fatal errors; ScannerOptions{} keeps the permissive low-level behavior.

Supported Inputs

  • Plain .warc
  • Record-at-a-time gzip .warc.gz
  • WARC-zstd .warc.zst / .warc.zstd, including prefix dictionary frames
Other Compression Formats

xz, bzip2, and LZ4 WARC files are generally compressed as one whole file; I have not found real-world per-record usage comparable to gzip or WARC-zstd. For those whole-file envelopes, use github.com/saveweb/decodedsource or another outer-layer decoder.

Remote Sources

To read WARC files from HTTP, WebDAV, S3, FTP, SMB, or other rclone-backed locations, use github.com/saveweb/remotesource.

WARC Terminology

This package follows the WARC grammar's hierarchy:

  • A record header is the WARC version line followed by the record's WARC named fields and the terminating empty CRLF line. It is represented by RecordHeader; its individual named fields are WARCField values.
  • An application/warc-fields block contains WARC named fields without a WARC version line. It is represented by WARCFields and parsed with ParseWARCFields.
  • The record block begins after the record header and contains exactly the number of octets declared by Content-Length.
  • A WARC payload is a record-type-specific subset of the block. unwarc does not infer that subset: RecordReader.Block, OpenBlock, and OpenBlockRange return block bytes. For an application/http response block, that includes both the HTTP header section and body.
  • The record terminator is the CRLF CRLF following the record block.

Record headers and application/warc-fields blocks therefore share named-field syntax, but they are not the same structure.

Validation Policies

Use DefaultScannerOptions for normal reading. It enables automatic compression detection and makes the common recoverable validation issues fatal:

scanner, err := unwarc.NewScannerFromSource(source, unwarc.DefaultScannerOptions())

The ScannerOptions{} zero value remains a low-level, permissive mode: recoverable format problems are reported through RecordRef.Issues() instead of being fatal. Applications can independently make specific conditions fatal with:

  • RequireRecordTrailer
  • RequireZstdFrameContentSize
  • RequireZstdFrameChecksum
  • RequireZstdRecordIsolation

The zstd record-isolation option rejects a frame that contributes bytes to more than one WARC record. It still permits one record to span multiple frames.

Without the corresponding requirement, zstd frames without Frame_Content_Size are decoded as streams and can still be lazy-opened after finalization when their compressed range is known and the record covers the whole frame.

The zero-value policies also accept practical, non-conforming layouts such as a solid gzip member or a zstd frame containing bytes from multiple WARC records. These layouts receive diagnostics. With a random-access source, reopening starts at the containing compression-unit boundary and discards decoded bytes before the requested record; without one, the records remain available through sequential streaming with AccessStreamOnly.

WARC version lines, header CRLF framing, and named-field syntax are always parsed strictly. Set ScannerOptions.Resynchronize to permit extra complete CRLF lines at record boundaries. It is disabled by default and never skips arbitrary bytes or relaxes parsing inside a record header.

Folded WARC Named Fields

WARC 1.0 and 1.1 allow a named field to continue on lines beginning with a space or tab. The named-field syntax is shared by fields inside record headers and by application/warc-fields blocks such as the record block of a typical warcinfo record. By default, unwarc accepts these fields for compatibility, replaces each continuation boundary with a single space, and sets WARCField.Folded.

RecordHeader.HasFoldedFields reports folding in a record header, and WARCFields.HasFoldedFields reports it in a parsed fields block. RecordRef.RawHeader always preserves the original record-header bytes.

Set ScannerOptions.FoldedFields to FoldedFieldReject when an application wants to reject continuation lines:

scanner, err := unwarc.NewScanner(r, unwarc.ScannerOptions{
	Compression:  unwarc.CompressionUnknown,
	FoldedFields: unwarc.FoldedFieldReject,
})

OpenWARCZstdSeekIndexWithOptions provides the same policy for reverse-built seek indexes. Rejection returns ErrFoldedWARCField; accepted folded fields are not reported as malformed-record issues because they are valid WARC syntax.

Use ParseWARCFields for an application/warc-fields block:

fields, err := unwarc.ParseWARCFields(block, unwarc.WARCFieldsOptions{
	FoldedFields: unwarc.FoldedFieldAccept,
})
if err != nil {
	return err
}
software, _ := fields.Get("software")

ScannerOptions.MaxBufferedZstdFrameSize bounds the in-memory fast path for WARC-zstd frames. Frames without Frame_Content_Size, frames larger than this limit, and frames whose compressed bytes exceed it are decoded with a streaming fallback instead of being buffered whole.

One-Pass Block Usage

Use NextRecord when you want to process each WARC record block in file order. It returns a RecordReader that owns the active record lifecycle and exposes its block through Block. This is the fast path for gzip because each compressed member is decompressed once. It works with both NewScanner and NewScannerFromSource.

source := unwarc.NewFileSource("crawl.warc.gz")
scanner, err := unwarc.NewScannerFromSource(source, unwarc.DefaultScannerOptions())
if err != nil {
	return err
}
defer scanner.Close()

for {
	record, err := scanner.NextRecord()
	if errors.Is(err, io.EOF) {
		break
	}
	if err != nil {
		return err
	}
	ref := record.Ref()

	warcType, _ := ref.Header.Get("WARC-Type")
	fmt.Println(warcType, ref.ContentLength)

	_, err = io.Copy(io.Discard, record.Block())
	closeErr := record.Close()
	if err != nil {
		return err
	}
	if closeErr != nil {
		return closeErr
	}

	// After the block has been read or closed, the same ref has final
	// location metadata and may be lazy-opened later if its access mode allows.
	if !ref.Finalized() {
		return fmt.Errorf("record was not finalized")
	}
}
if err := scanner.Err(); err != nil {
	return err
}

References returned by RecordReader.Ref may remain unfinalized until the block reaches EOF or the record is closed. Check RecordRef.Finalized() when using the streaming API. Calling OpenRaw or OpenBlock before finalization returns ErrRecordLocationPending. While a NextRecord reader is active, Scanner.RecordRef() returns nil; use record.Ref() for header inspection before finalization. Calling NextRecord, Next, Err, or Scanner.Close automatically closes and drains an active record; any trailer or compression error encountered during that finalization is returned or retained by the scanner.

Lazy Random-Access Usage

Use NewScannerFromSource with Next when you want to scan first and lazily reopen records later. The source can reopen byte ranges, so finalized record references remain usable after scanning. For compressed inputs this path may re-read and re-decompress compressed data when OpenRaw or OpenBlock is called. Keep the source backing bytes stable until all lazy readers are closed; FileSource reopens by path, so the file must not be replaced while collected references are being processed.

After finalization, RecordRef.Location() reports the record's decoded WARC stream range and its AccessMode. Use RawDecodeCost, BlockDecodeCost, or BlockRangeDecodeCost to inspect the encoded ranges that must be reopened and the decoded bytes that must be discarded before output starts. Whole-file or solid compression often reports an encoded range starting at an earlier compression unit, with a non-zero decoded discard count.

OpenRaw, OpenBlock, and OpenBlockRange open any lazy-loadable record. New code that wants to avoid hidden expensive work should check decode cost before opening. RecordRef.BlockIndex() separately exposes parsed frame mappings when an indexed input provides them.

source := unwarc.NewFileSource("crawl.warc.zst")
scanner, err := unwarc.NewScannerFromSource(source, unwarc.DefaultScannerOptions())
if err != nil {
	return err
}
defer scanner.Close()

var refs []*unwarc.RecordRef
for scanner.Next() {
	refs = append(refs, scanner.RecordRef())
}
if err := scanner.Err(); err != nil {
	return err
}

for _, ref := range refs {
	cost, ok := ref.BlockDecodeCost()
	if !ok {
		continue
	}
	if cost.DecodedDiscardBytes > 64<<20 {
		continue
	}
	block, err := ref.OpenBlock()
	if err != nil {
		return err
	}
	_, err = io.Copy(io.Discard, block)
	closeErr := block.Close()
	if err != nil {
		return err
	}
	if closeErr != nil {
		return closeErr
	}
}

Pipelined Reference Processing

You can also scan finalized references in one goroutine and process them with a worker pool. This overlaps sequential boundary discovery with concurrent lazy block reads. The channel should be bounded so slow workers apply backpressure to the scanner instead of accumulating every reference in memory.

This pattern still re-reads and re-decompresses compressed data in the workers. Use NextRecord instead when the main goal is one-pass gzip processing.

source := unwarc.NewFileSource("crawl.warc.gz")
scanner, err := unwarc.NewScannerFromSource(source, unwarc.DefaultScannerOptions())
if err != nil {
	return err
}
defer scanner.Close()

const workers = 8
refs := make(chan *unwarc.RecordRef, workers*2)
errc := make(chan error, workers+1)

var wg sync.WaitGroup
for i := 0; i < workers; i++ {
	wg.Add(1)
	go func() {
		defer wg.Done()
		for ref := range refs {
			block, err := ref.OpenBlock()
			if err != nil {
				errc <- err
				return
			}

			_, readErr := io.Copy(io.Discard, block)
			closeErr := block.Close()
			if readErr != nil {
				errc <- readErr
				return
			}
			if closeErr != nil {
				errc <- closeErr
				return
			}
		}
	}()
}

for scanner.Next() {
	select {
	case refs <- scanner.RecordRef():
	case err := <-errc:
		close(refs)
		wg.Wait()
		return err
	}
}
scanErr := scanner.Err()
close(refs)
wg.Wait()

select {
case err := <-errc:
	return err
default:
	return scanErr
}

If downstream work must commit only after the entire file validates, write worker results to a staging area and publish them after scanner.Err() returns nil. When validation requirements are enabled, a later scan error can otherwise leave earlier records already processed.

WARC-zstd Seek Index

OpenWARCZstdSeekIndex supports an optional enhanced WARC-zstd profile for fast reverse indexing. In this profile, each record is encoded as:

zstd frame: WARC record-header bytes
one or more zstd frames: record-block bytes, optionally chunked,
                         plus record trailer
skippable frame: record-local zstd seek table for the frames above

Here, "WARC record-header bytes" means the complete record header: version line, WARC named fields, and the terminating empty CRLF line. The seek table is local to the record, so a record copied into another WARC file still carries meaningful frame sizes. The index builder walks backward from the file tail, reads each record-local seek table, and decodes only the record-header frame. Block frames are not decoded while building the index; OpenBlock can later reopen only the block frame ranges.

Small records can use a single block frame. Large records can split block bytes across many smaller frames. When available, RecordRef.BlockIndex() maps each block-producing compressed frame to its block-relative byte range, and OpenBlockRange uses those mappings to reopen only overlapping frames. A frame that contains only the WARC record trailer is not part of the block index because it contributes no block bytes. Without a block index, block reads fall back to the record's general decode plan.

For HTTP response/request records, the WARC record block contains an HTTP message. Writers may split that block at the HTTP header/body boundary as a best-effort optimization:

zstd frame: WARC record-header bytes
zstd frame: HTTP header bytes
one or more zstd frames: HTTP body bytes
optional zstd frame: WARC record trailer
skippable frame: record-local zstd seek table

The table still stores only generic frame sizes. The reader treats these as ordinary block frames; higher layers that parse HTTP can use RecordRef.BlockIndex() plus their own parsed HTTP header length to find the first body frame. The reader does not label frames as HTTP header or body.

Writer recommendation:

  • For small records, prefer the compact layout: one WARC record-header frame and one block-plus-trailer frame. The extra frame boundaries are rarely worth it.
  • For large HTTP responses, split best-effort at the HTTP message boundary and then chunk the HTTP body into independently seekable frames. This gives viewers and extractors a cheap body starting point and lets OpenBlockRange decode only the body chunks that overlap a requested range.
  • Splitting only the HTTP header from a single large body frame can slightly improve compression and records useful structure, but it does not materially speed up random body ranges by itself. Body chunking is what changes range access cost.
  • If the HTTP boundary cannot be identified confidently, fall back to the generic block-frame layout and preserve the record-block bytes unchanged.

For Content-Length: 0 records, the recommended compact form is one zstd frame containing the WARC record header plus record trailer, followed by a one-entry record-local seek table. The reader also accepts the two-frame form with a WARC record-header frame and a trailer-only frame, but OpenBlock returns an empty reader without reopening either frame.

source := unwarc.NewFileSource("crawl.seek.warc.zst")
index, err := unwarc.OpenWARCZstdSeekIndex(source)
if errors.Is(err, unwarc.ErrNotSeekIndexed) {
	// Fall back to NewScannerFromSource when the input is ordinary WARC-zstd
	// or a mixed stream.
	return scanForward(source)
}
if err != nil {
	return err
}

for _, ref := range index.Records() {
	block, err := ref.OpenBlock()
	if err != nil {
		return err
	}
	_, err = io.Copy(io.Discard, block)
	closeErr := block.Close()
	if err != nil {
		return err
	}
	if closeErr != nil {
		return closeErr
	}
}

This first implementation intentionally rejects mixed streams instead of combining reverse indexing with a forward scan. If any suffix does not match the record-local profile, callers get ErrNotSeekIndexed and can choose their own fallback policy.

Stream-Only Usage

Use NewScanner for stream-only validation or record listing. A stream-only scanner cannot lazy-open record bytes after a record has passed, so do not call OpenRaw or OpenBlock on its references.

f, err := os.Open("crawl.warc.gz")
if err != nil {
	return err
}
defer f.Close()

scanner, err := unwarc.NewScanner(f, unwarc.DefaultScannerOptions())
if err != nil {
	return err
}

for scanner.Next() {
	ref := scanner.RecordRef()
	warcType, _ := ref.Header.Get("WARC-Type")
	location, ok := ref.Location()
	if !ok {
		return fmt.Errorf("record was not finalized")
	}
	fmt.Println(warcType, ref.ContentLength, location.Access)
}
if err := scanner.Err(); err != nil {
	return err
}

Error Handling

Sentinel errors are exported for errors.Is, including:

  • ErrInvalidWARCHeader
  • ErrInvalidWARCFields
  • ErrInvalidWARCField
  • ErrMissingContentLength
  • ErrInvalidContentLength
  • ErrFoldedWARCField
  • ErrMissingRecordTrailer
  • ErrUnsupportedCompression
  • ErrInvalidWARCZstd
  • ErrRecordLocationPending
  • ErrNotSeekIndexed

Verification

make verify

The verify target runs formatting checks, tests, race tests, vet, build, and a short fuzz smoke. If golangci-lint is installed, it is included automatically.

Useful focused commands:

make test
make race
make fuzz-smoke

Corpus Regression

Small real-world fixtures live under testdata/corpus and cover Common Crawl, gowarc, and Zeno outputs, including damaged .open files and a Zeno WARC-zstd sample that the permissive zero-value policies can scan but RequireZstdFrameContentSize rejects.

Large local corpora can be scanned without checking them into the repository:

UNWARC_CORPUS_DIR=/path/to/warcs go test -run TestExternalCorpusSmoke ./...
UNWARC_CORPUS_PATHS="/path/a.warc.gz:/path/b.warc.zst" go test -run TestExternalCorpusSmoke ./...
UNWARC_CORPUS_LIMIT=10 UNWARC_CORPUS_RECORD_LIMIT=25 UNWARC_CORPUS_DIR=/path/to/warcs go test -run TestExternalCorpusSmoke ./...

Corpus Benchmarks

The checked-in corpus benchmark is intended for long-term regression tracking without external files:

make bench-corpus

It runs stream block access, source-backed stream block access, and source-backed scan-then-lazy-reopen block access over small gzip and zstd fixtures, including dictionary and no-Frame_Content_Size zstd cases. Use the larger real corpus benchmark below when you need absolute throughput numbers on production-sized inputs.

The Benchmark GitHub Actions workflow runs the same corpus benchmark on pull requests, pushes to main, and manual dispatch. Pure Go benchmarks run on Linux, macOS, and Windows with a fixed -cpu=1, seven samples, and a shorter per-sample benchtime to reduce hosted runner scheduling noise. Pushes to main publish benchmark history to the gh-pages branch under dev/bench/v2/* without alert comments; benchmark collection runs in parallel, while the short history-publishing step is serialized to avoid concurrent gh-pages pushes. Pull requests compare against the stored history and leave job summaries without updating history.

This repository serves the benchmark dashboard from the gh-pages branch. For a fork or a fresh repository, initialize that branch once and configure GitHub Pages to serve it:

git switch --orphan gh-pages
git commit --allow-empty -m "Initialize benchmark pages"
git push origin gh-pages:gh-pages
git switch -

Real Corpus Benchmarks

Benchmarks for large local corpora are gated by an environment variable:

UNWARC_BENCH_WARC=/path/to/input.warc.gz go test -run '^$' -bench BenchmarkRealWARC -benchtime=1x -benchmem

The benchmark compares stream block access, source-backed stream block access, and source-backed scan-then-lazy-reopen block access. The first two are the one-pass paths; the lazy reopening benchmark intentionally measures the cost of re-reading compressed bytes. Use -bench 'BenchmarkRealWARC/source_stream_block$' or another sub-benchmark suffix to run one path at a time.

Documentation

Overview

Package unwarc scans WARC files and returns lightweight record references.

The scanner supports uncompressed WARC, record-at-a-time gzip, and WARC-zstd including prefix dictionary frames. When a random-access source is provided, finalized record references can lazily reopen raw records or record-block bytes without materializing the whole input. Scanner.NextRecord returns a RecordReader for one-pass in-order processing. RecordReader.Block exposes the WARC record block, and RecordReader.Ref is finalized after the block reaches EOF or the record is closed. Scanner.RecordRef returns only finalized references. Lazy reopening from a source may re-read and re-decompress compressed bytes. RecordRef exposes decode-cost methods so callers can choose when non-exact compressed layouts are acceptable. The package does not infer the WARC payload, which may be a record-type-specific subset of the record block.

WARC-zstd scanning buffers only small known-size frames. Frames without Frame_Content_Size or beyond ScannerOptions.MaxBufferedZstdFrameSize are decoded with a streaming fallback.

WARC 1.0/1.1 folded named fields are accepted and unfolded by default in record headers and ParseWARCFields. WARCField.Folded reports their presence, while the relevant options can reject them when required.

OpenWARCZstdSeekIndex supports an optional record-local WARC-zstd seek profile. It walks backward through seekable-table skippable frames and builds finalized references by decoding only WARC record-header frames; block frames are reopened lazily by range when needed.

WARC version lines, header CRLF framing, and named-field syntax are parsed strictly by default. ScannerOptions.Resynchronize can explicitly permit extra CRLF lines at record boundaries. Independent ScannerOptions requirements can make malformed record trailers, missing zstd Frame_Content_Size or Content_Checksum fields, and zstd frames shared by multiple records fatal. DefaultScannerOptions returns the recommended strict preset for normal scanning.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidWARCHeader reports an invalid WARC record header, which consists
	// of a version line followed by WARC named fields.
	ErrInvalidWARCHeader = errors.New("invalid WARC record header")

	// ErrInvalidWARCFields reports malformed application/warc-fields content.
	ErrInvalidWARCFields = errors.New("invalid application/warc-fields block")

	// ErrInvalidWARCField reports malformed WARC named-field syntax. It may be
	// wrapped by ErrInvalidWARCHeader or ErrInvalidWARCFields depending on where
	// the field appeared.
	ErrInvalidWARCField = errors.New("invalid WARC named field")

	// ErrMissingContentLength reports a WARC record without Content-Length.
	ErrMissingContentLength = errors.New("missing Content-Length")

	// ErrInvalidContentLength reports a negative or unparsable Content-Length.
	ErrInvalidContentLength = errors.New("invalid Content-Length")

	// ErrDuplicateContentLength reports multiple Content-Length fields in a WARC
	// record.
	ErrDuplicateContentLength = errors.New("duplicate Content-Length")

	// ErrFoldedWARCField reports a folded WARC named field when the configured
	// folded-field policy rejects continuations.
	ErrFoldedWARCField = errors.New("folded WARC field")

	// ErrMissingRecordTrailer reports a missing or invalid record trailer.
	ErrMissingRecordTrailer = errors.New("missing record trailer")

	// ErrUnsupportedCompression reports an unknown compression enum value.
	ErrUnsupportedCompression = errors.New("unsupported compression")

	// ErrInvalidWARCZstd reports a required WARC-zstd validation failure.
	ErrInvalidWARCZstd = errors.New("invalid WARC-zstd")

	// ErrRecordLocationPending reports an attempt to lazily reopen a record
	// before the scanner has finalized its compressed and uncompressed ranges.
	ErrRecordLocationPending = errors.New("record location is pending")

	// ErrNotSeekIndexed reports input that does not fully match the
	// record-local WARC-zstd seek index profile.
	ErrNotSeekIndexed = errors.New("not a record-local WARC-zstd seek-indexed stream")
)

Functions

This section is empty.

Types

type AccessMode

type AccessMode int

AccessMode describes how a RecordRef can be lazily reopened.

const (
	// AccessInvalid means the scanner could not resolve a usable location.
	AccessInvalid AccessMode = iota
	// AccessExact means the compressed ranges map exactly to the record.
	AccessExact
	// AccessFromCompressionUnitStart means lazy reads restart at a compression
	// unit boundary and discard preceding uncompressed bytes.
	AccessFromCompressionUnitStart
	// AccessStreamOnly means the record was found but cannot be lazily reopened.
	AccessStreamOnly
)

func (AccessMode) String

func (m AccessMode) String() string

type BlockFrameMapping

type BlockFrameMapping struct {
	Compressed Range
	Block      Range
}

BlockFrameMapping maps one compressed frame to the record-block bytes it contributes. Block is relative to the WARC record block.

type BlockIndex

type BlockIndex struct {
	Frames []BlockFrameMapping
}

BlockIndex describes optional frame-level random access within a record block. It is available only when the input carries a recognized block index.

type Compression

type Compression int

Compression identifies the compression envelope around a WARC stream.

const (
	// CompressionPlain is an uncompressed WARC stream.
	CompressionPlain Compression = iota
	// CompressionGzip is a gzip-compressed WARC stream.
	CompressionGzip
	// CompressionZstd is a WARC-zstd stream.
	CompressionZstd
	// CompressionUnknown asks the scanner to detect compression when possible.
	CompressionUnknown
)

func (Compression) String

func (c Compression) String() string

type DecodeCost

type DecodeCost struct {
	// EncodedRanges are absolute RandomAccessSource byte ranges to reopen.
	// Ranges may be discontiguous when a record spans multiple independently
	// compressed frames or members. A range with negative Size means decoding
	// starts at Off and continues until enough decoded output has been produced.
	// EncodedRanges[0].Off may be passed to NewScannerAt to start directly at
	// this record only when the corresponding RecordLocation.Access is
	// AccessExact. For AccessFromCompressionUnitStart it starts at an earlier
	// frame or member and DecodedDiscardBytes describes the intervening output.
	EncodedRanges []Range
	// DecodedDiscardBytes is the decoded byte count discarded before the
	// returned reader starts producing bytes.
	DecodedDiscardBytes int64
	// DecodedOutputBytes is the decoded byte count returned by the lazy reader.
	DecodedOutputBytes int64
}

DecodeCost describes the storage bytes reopened and decoded bytes discarded before a lazy read returns its requested output.

type FileSource

type FileSource struct {
	Path string
}

FileSource opens ranges from a file path. The path must continue to refer to the same file contents while lazy RecordRef readers are in use.

func NewFileSource

func NewFileSource(path string) FileSource

NewFileSource returns a source backed by path.

func (FileSource) Open

func (s FileSource) Open() (io.ReadCloser, error)

func (FileSource) OpenAt

func (s FileSource) OpenAt(off int64) (io.ReadCloser, error)

func (FileSource) OpenRange

func (s FileSource) OpenRange(off, size int64) (io.ReadCloser, error)

func (FileSource) Size

func (s FileSource) Size() (int64, error)

type FoldedFieldPolicy

type FoldedFieldPolicy int

FoldedFieldPolicy controls whether WARC named-field continuation lines are accepted in record headers and application/warc-fields blocks. WARC 1.0 and 1.1 permit continuation lines that begin with space or tab.

https://github.com/iipc/warc-specifications/issues/74

const (
	// FoldedFieldAccept unfolds continuation lines and marks the affected
	// WARCField values. This is the default for backward compatibility.
	FoldedFieldAccept FoldedFieldPolicy = iota
	// FoldedFieldReject returns ErrFoldedWARCField when a continuation line is
	// encountered.
	FoldedFieldReject
)

type Issue

type Issue struct {
	Code    IssueCode
	Message string
}

Issue describes a non-fatal condition found while scanning a record.

type IssueCode

type IssueCode int

IssueCode identifies a non-fatal record or compression layout issue.

const (
	// IssueMissingContentLength is reserved for callers that classify missing
	// Content-Length. The scanner currently treats it as fatal.
	IssueMissingContentLength IssueCode = iota + 1
	// IssueInvalidContentLength is reserved for callers that classify invalid
	// Content-Length. The scanner currently treats it as fatal.
	IssueInvalidContentLength
	// IssueMissingRecordTrailer means the record trailer was missing or invalid.
	IssueMissingRecordTrailer
	// IssueFrameContainsMultipleRecords means a zstd frame does not align with
	// a single WARC record boundary.
	IssueFrameContainsMultipleRecords
	// IssueSolidGzipMember means a gzip member contains a partial record or
	// more than one record.
	IssueSolidGzipMember
	// IssueRecordSpansGzipMembers means one WARC record spans multiple gzip
	// members.
	IssueRecordSpansGzipMembers
	// IssueZstdSkippableFrame is reserved for zstd skippable-frame diagnostics.
	IssueZstdSkippableFrame
	// IssueUnsupportedCompression means the compression mode is not supported.
	IssueUnsupportedCompression
	// IssueZstdFrameMissingContentSize means a WARC-zstd frame lacks
	// Frame_Content_Size.
	IssueZstdFrameMissingContentSize
	// IssueZstdFrameMissingChecksum means a WARC-zstd frame lacks
	// Content_Checksum.
	IssueZstdFrameMissingChecksum
)

type RandomAccessSource

type RandomAccessSource interface {
	Source
	OpenRange(off, size int64) (io.ReadCloser, error)
	OpenAt(off int64) (io.ReadCloser, error)
	Size() (int64, error)
}

RandomAccessSource opens whole-file and byte-range readers for lazy record access. Implementations must return independent readers from each Open, OpenRange, and OpenAt call; RecordRef.OpenRaw and RecordRef.OpenBlock may call them concurrently after scanning has finished. The backing bytes must remain stable until every reader opened from the collected RecordRef values has been closed.

type Range

type Range struct {
	// Off is the first byte offset in the range.
	Off int64
	// Size is the number of bytes in the range, or -1 when the end is unknown.
	Size int64
}

Range describes a byte range. A negative Size means the end is unknown.

func (Range) End

func (r Range) End() int64

End returns the first byte offset after the range, or -1 when Size is unknown.

func (Range) Valid

func (r Range) Valid() bool

Valid reports whether the range has a non-negative offset and known size.

type ReaderAtSource

type ReaderAtSource struct {
	ReaderAt io.ReaderAt
	Reader   func() (io.ReadCloser, error)
	Length   int64
	Closer   io.Closer
}

ReaderAtSource adapts an io.ReaderAt into a RandomAccessSource. If Closer is set, call Close only after all scanners and RecordRef readers using the source have finished.

func NewReaderAtSource

func NewReaderAtSource(readerAt io.ReaderAt, size int64, open func() (io.ReadCloser, error)) ReaderAtSource

NewReaderAtSource returns a source backed by readerAt. The open function is optional; when nil, Open uses a section reader over readerAt.

func (ReaderAtSource) Close

func (s ReaderAtSource) Close() error

func (ReaderAtSource) Open

func (s ReaderAtSource) Open() (io.ReadCloser, error)

func (ReaderAtSource) OpenAt

func (s ReaderAtSource) OpenAt(off int64) (io.ReadCloser, error)

func (ReaderAtSource) OpenRange

func (s ReaderAtSource) OpenRange(off, size int64) (io.ReadCloser, error)

func (ReaderAtSource) Size

func (s ReaderAtSource) Size() (int64, error)

type Record

type Record struct {
	Ref  *RecordRef
	Data []byte
}

Record is a materialized WARC record.

func NewRecordFromBytes

func NewRecordFromBytes(data []byte) (_ *Record, err error)

NewRecordFromBytes parses a single uncompressed WARC record from data.

type RecordHeader

type RecordHeader struct {
	Version string
	Fields  []WARCField
}

RecordHeader is a parsed WARC record header. A record header consists of the WARC version line followed by WARC named fields. It is distinct from an application/warc-fields record block, which contains fields without a version line.

func (RecordHeader) Get

func (h RecordHeader) Get(name string) (string, bool)

Get returns the first WARC named-field value whose name matches case insensitively.

func (RecordHeader) HasFoldedFields

func (h RecordHeader) HasFoldedFields() bool

HasFoldedFields reports whether any named field used a continuation line.

type RecordLocation

type RecordLocation struct {
	// Uncompressed is the record's range in this Scanner's decoded stream. It is
	// relative to the point where the scanner started, so a Scanner created by
	// NewScannerAt reports its first record at or near offset zero. It is not an
	// absolute file offset and must not be passed to NewScannerAt.
	Uncompressed Range
	// Access describes the starting point required for lazy reopening.
	Access AccessMode
}

RecordLocation describes where a finalized record appears in the scanner's decoded WARC stream and how it can be reopened.

type RecordReader

type RecordReader struct {
	// contains filtered or unexported fields
}

RecordReader is the active streaming view of one WARC record. Ref is available immediately after the record header is parsed, but its location is finalized only after Block reaches EOF or Close completes.

func (*RecordReader) Block

func (r *RecordReader) Block() io.Reader

Block returns a reader for the WARC record block declared by Content-Length. The returned reader is owned by the RecordReader and must not be used after Close. Reading it to EOF finalizes the record.

func (*RecordReader) Close

func (r *RecordReader) Close() error

Close drains any unread block bytes, validates the record trailer, and finalizes the record reference and compression mapping.

func (*RecordReader) Read

func (r *RecordReader) Read(p []byte) (int, error)

Read reads bytes from the WARC record block.

func (*RecordReader) Ref

func (r *RecordReader) Ref() *RecordRef

Ref returns the record reference associated with this reader. Header fields and ContentLength are available immediately; location-dependent operations require Ref().Finalized() to report true.

type RecordRef

type RecordRef struct {
	// Header is the parsed WARC record header: version plus named fields.
	Header RecordHeader
	// RawHeader preserves the serialized record-header bytes through the
	// terminating empty CRLF line.
	RawHeader []byte

	// ContentLength is the record-block length declared by Content-Length.
	ContentLength int64
	// HeaderLen is the byte length of RawHeader in the uncompressed record.
	HeaderLen int64
	// TrailerLen is the number of trailer bytes consumed after the record block.
	TrailerLen int64
	// contains filtered or unexported fields
}

RecordRef describes a scanned WARC record and how to reopen it after its location has been finalized.

func (*RecordRef) BlockDecodeCost

func (r *RecordRef) BlockDecodeCost() (DecodeCost, bool)

BlockDecodeCost returns the cost of lazily opening the WARC record block declared by Content-Length. The second result is false while the record is pending or when the block cannot be reopened from a random-access source.

func (*RecordRef) BlockIndex

func (r *RecordRef) BlockIndex() (BlockIndex, bool)

BlockIndex returns optional frame-level block mappings. The returned slice is independent of the RecordRef and may be modified by the caller.

func (*RecordRef) BlockRangeDecodeCost

func (r *RecordRef) BlockRangeDecodeCost(off, size int64) (DecodeCost, bool, error)

BlockRangeDecodeCost returns the cost of lazily opening a byte range within the WARC record block. The second result is false while the record is pending or when the range cannot be reopened from a random-access source.

func (*RecordRef) Finalized

func (r *RecordRef) Finalized() bool

Finalized reports whether the record location is complete. References returned by Scanner.Next are finalized before they are exposed; references exposed by RecordReader.Ref are finalized only after the record block reaches EOF or the RecordReader is closed.

func (*RecordRef) Issues

func (r *RecordRef) Issues() []Issue

Issues returns non-fatal diagnostics discovered while scanning the record.

func (*RecordRef) Location

func (r *RecordRef) Location() (RecordLocation, bool)

Location returns the finalized record location. The second result is false while a streaming RecordReader is still active.

func (*RecordRef) Materialize

func (r *RecordRef) Materialize() (*Record, error)

Materialize reads the complete raw record into memory.

func (*RecordRef) OpenBlock

func (r *RecordRef) OpenBlock() (io.ReadCloser, error)

OpenBlock opens the WARC record block declared by Content-Length.

func (*RecordRef) OpenBlockRange

func (r *RecordRef) OpenBlockRange(off, size int64) (io.ReadCloser, error)

OpenBlockRange opens a byte range within the WARC record block. When block-frame metadata is available, it reopens only the compressed frames overlapping the requested block range; otherwise it falls back to OpenBlock and discards bytes before off.

func (*RecordRef) OpenRaw

func (r *RecordRef) OpenRaw() (io.ReadCloser, error)

OpenRaw opens the complete uncompressed record bytes, including the WARC record header, record block, and trailer.

func (*RecordRef) RawDecodeCost

func (r *RecordRef) RawDecodeCost() (DecodeCost, bool)

RawDecodeCost returns the cost of lazily opening the complete uncompressed record bytes, including the WARC record header, record block, and trailer. The second result is false while the record is pending or when the record cannot be reopened from a random-access source.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner incrementally reads WARC records from a stream.

func NewScanner

func NewScanner(r io.Reader, opts ScannerOptions) (*Scanner, error)

NewScanner creates a scanner over r. Lazy reopening is unavailable because plain readers do not provide random access.

func NewScannerAt

func NewScannerAt(source RandomAccessSource, compressedOffset int64, opts ScannerOptions) (*Scanner, error)

NewScannerAt creates a scanner whose input starts at compressedOffset in source. compressedOffset is an absolute byte offset in the stored input and must point to a decodable compression-unit boundary: a WARC record boundary for plain input, a gzip member boundary, or an independently decodable zstd frame boundary.

RecordLocation.Uncompressed values are relative to the decoded stream beginning at compressedOffset and therefore restart from zero. RecordRef.RawDecodeCost and related decode-cost methods continue to address the original source using absolute encoded offsets. Do not pass a RecordLocation.Uncompressed offset to NewScannerAt.

func NewScannerFromSource

func NewScannerFromSource(source RandomAccessSource, opts ScannerOptions) (*Scanner, error)

NewScannerFromSource creates a scanner over source. Finalized RecordRef values can reopen record bytes lazily when their Access mode permits it.

func (*Scanner) Close

func (s *Scanner) Close() error

Close finalizes any active record and closes the underlying readers.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns the first non-EOF error encountered by the scanner.

func (*Scanner) Next

func (s *Scanner) Next() bool

Next advances to the next record. It returns false on EOF or error; Err reports the final error.

func (*Scanner) NextRecord

func (s *Scanner) NextRecord() (*RecordReader, error)

NextRecord advances to the next WARC record and returns its streaming record reader. The reader exposes the parsed header and streams the record block. Trailer validation, location resolution, and non-fatal diagnostics are finalized when the block is exhausted or the record is closed. Advancing automatically closes and drains the previous record, returning any error produced while finalizing it.

It returns io.EOF when no more records are available.

func (*Scanner) RecordRef

func (s *Scanner) RecordRef() *RecordRef

RecordRef returns the current finalized record reference. It returns nil before the first record and while a NextRecord reader is still active. Use RecordReader.Ref to inspect header fields before the record is finalized.

type ScannerOptions

type ScannerOptions struct {
	// Compression selects the input envelope. Use CompressionUnknown to detect
	// gzip, zstd, or plain input from the stream or source name.
	Compression Compression

	// RequireRecordTrailer makes a missing, partial, or invalid WARC record
	// trailer fatal instead of recording IssueMissingRecordTrailer.
	RequireRecordTrailer bool

	// RequireZstdFrameContentSize rejects zstd frames without
	// Frame_Content_Size.
	RequireZstdFrameContentSize bool

	// RequireZstdFrameChecksum rejects zstd frames without Content_Checksum.
	RequireZstdFrameChecksum bool

	// RequireZstdRecordIsolation rejects a zstd frame that contributes bytes to
	// more than one WARC record. A single record may still span multiple frames.
	RequireZstdRecordIsolation bool

	// FoldedFields controls named-field continuation lines within the WARC
	// record header. The zero value accepts and unfolds them for WARC 1.0/1.1
	// compatibility. Rejecting them returns ErrFoldedWARCField.
	FoldedFields FoldedFieldPolicy

	// Resynchronize permits extra CRLF lines at record boundaries. The default
	// is false. It does not skip arbitrary bytes or relax header parsing.
	Resynchronize bool

	// MaxBufferedZstdFrameSize bounds the per-frame fast-path buffer used while
	// scanning WARC-zstd. Frames without Frame_Content_Size, frames whose
	// declared content size exceeds this value, or frames whose compressed bytes
	// cross this value are decoded as streams instead. The default is
	// 16 MiB. Set a negative value to force streaming for all zstd frames.
	MaxBufferedZstdFrameSize int64
}

ScannerOptions configures stream decompression and validation.

func DefaultScannerOptions

func DefaultScannerOptions() ScannerOptions

DefaultScannerOptions returns the recommended options for normal WARC scanning: automatic compression detection and strict treatment of recoverable trailer and WARC-zstd layout issues.

The ScannerOptions zero value is still accepted for low-level callers that want permissive validation and explicit plain-input scanning.

type Source

type Source interface {
	Open() (io.ReadCloser, error)
}

Source opens a fresh reader for a WARC input.

type WARCField

type WARCField struct {
	Name  string
	Value string

	// Folded reports whether Value was unfolded from one or more continuation
	// lines. RecordRef.RawHeader preserves original record-header bytes.
	Folded bool
}

WARCField is a parsed WARC named field. The same named-field syntax is used inside record headers and application/warc-fields blocks.

type WARCFields

type WARCFields struct {
	// Fields contains only named fields; application/warc-fields has no WARC
	// version line.
	Fields []WARCField
}

WARCFields is parsed content using the application/warc-fields syntax.

func ParseWARCFields

func ParseWARCFields(data []byte, opts WARCFieldsOptions) (WARCFields, error)

ParseWARCFields parses an application/warc-fields block. It accepts folded fields by default and does not modify data.

func (WARCFields) Get

func (f WARCFields) Get(name string) (string, bool)

Get returns the first field value whose name matches case insensitively.

func (WARCFields) HasFoldedFields

func (f WARCFields) HasFoldedFields() bool

HasFoldedFields reports whether any field used WARC continuation lines.

type WARCFieldsOptions

type WARCFieldsOptions struct {
	// FoldedFields controls continuation lines. The zero value accepts and
	// unfolds them for WARC 1.0/1.1 compatibility.
	FoldedFields FoldedFieldPolicy
}

WARCFieldsOptions configures parsing of an application/warc-fields record block. Record-header parsing is configured through ScannerOptions or WARCZstdSeekIndexOptions instead.

type WARCZstdSeekIndex

type WARCZstdSeekIndex struct {
	// contains filtered or unexported fields
}

WARCZstdSeekIndex is a reverse-built index for the record-local WARC-zstd seek profile. Each indexed record is encoded as a zstd frame for the WARC record header, one or more zstd frames for record-block bytes plus the record trailer, and a zstd seekable-table skippable frame describing those data frames. Empty records may instead use a single zstd frame containing the WARC record header and trailer.

func OpenWARCZstdSeekIndex

func OpenWARCZstdSeekIndex(source RandomAccessSource) (*WARCZstdSeekIndex, error)

OpenWARCZstdSeekIndex opens a WARC-zstd input that is fully composed of record-local seekable streams and returns finalized record references without decoding block frames. If any suffix does not match the profile, it returns ErrNotSeekIndexed so callers can choose a normal forward scan instead.

func OpenWARCZstdSeekIndexWithOptions

func OpenWARCZstdSeekIndexWithOptions(source RandomAccessSource, opts WARCZstdSeekIndexOptions) (*WARCZstdSeekIndex, error)

OpenWARCZstdSeekIndexWithOptions is OpenWARCZstdSeekIndex with explicit WARC record-header parsing options.

func (*WARCZstdSeekIndex) Records

func (i *WARCZstdSeekIndex) Records() []*RecordRef

Records returns a copy of the indexed record references in file order.

type WARCZstdSeekIndexOptions

type WARCZstdSeekIndexOptions struct {
	// FoldedFields controls named-field continuation lines within record
	// headers. The zero value accepts and unfolds them for WARC 1.0/1.1
	// compatibility.
	FoldedFields FoldedFieldPolicy
}

WARCZstdSeekIndexOptions configures record-header parsing while building a record-local WARC-zstd seek index.

Directories

Path Synopsis
internal
benchjson command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址