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 ¶
- Variables
- type AccessMode
- type BlockFrameMapping
- type BlockIndex
- type Compression
- type DecodeCost
- type FileSource
- type FoldedFieldPolicy
- type Issue
- type IssueCode
- type RandomAccessSource
- type Range
- type ReaderAtSource
- type Record
- type RecordHeader
- type RecordLocation
- type RecordReader
- type RecordRef
- func (r *RecordRef) BlockDecodeCost() (DecodeCost, bool)
- func (r *RecordRef) BlockIndex() (BlockIndex, bool)
- func (r *RecordRef) BlockRangeDecodeCost(off, size int64) (DecodeCost, bool, error)
- func (r *RecordRef) Finalized() bool
- func (r *RecordRef) Issues() []Issue
- func (r *RecordRef) Location() (RecordLocation, bool)
- func (r *RecordRef) Materialize() (*Record, error)
- func (r *RecordRef) OpenBlock() (io.ReadCloser, error)
- func (r *RecordRef) OpenBlockRange(off, size int64) (io.ReadCloser, error)
- func (r *RecordRef) OpenRaw() (io.ReadCloser, error)
- func (r *RecordRef) RawDecodeCost() (DecodeCost, bool)
- type Scanner
- type ScannerOptions
- type Source
- type WARCField
- type WARCFields
- type WARCFieldsOptions
- type WARCZstdSeekIndex
- type WARCZstdSeekIndexOptions
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 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.
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 ¶
Record is a materialized WARC record.
func NewRecordFromBytes ¶
NewRecordFromBytes parses a single uncompressed WARC record from data.
type RecordHeader ¶
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 ¶
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 ¶
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 ¶
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) Next ¶
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.
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.