rq_go

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 6 Imported by: 0

README

RaptorQ Go Bindings

This repository contains Go bindings for the RaptorQ erasure coding library. RaptorQ is a Forward Error Correction (FEC) code that allows for efficient recovery of data from partial information. This package enables encoding files into RaptorQ symbols and decoding them back, providing resilience against data loss.

Key Features

  • Memory-Efficient Block Processing: Files are split into blocks for processing, with each block encoded separately to minimize memory usage
  • Built-in Resource Management: Explicit control over memory usage and concurrency limits
  • Flexible Configuration: Customizable symbol size, redundancy factor, and other parameters
  • Error Recovery: Can recover the original file even if some symbols are missing
  • Cross-Platform Support: Linux (amd64, arm64) and macOS (Intel, Apple Silicon)
  • Static Linking: Library is statically linked, making the final binary self-contained

Repository Structure

rq-go/
├── README.md                 # This file
├── go.mod                    # Root Go module file (lumera.build/rq-go)
├── raptorq.go                # Main Go binding code
├── raptorq_test.go           # Tests for the Go bindings
├── include/rq-library.h      # C header of the bundled library
├── lib/                      # Static rq-library builds, one per platform
│   ├── RQ_LIBRARY            # Which rq-library release they come from, with checksums
│   ├── darwin/amd64/librq_library.a
│   ├── darwin/arm64/librq_library.a
│   ├── linux/amd64/librq_library.a
│   └── linux/arm64/librq_library.a
└── test-client/              # Example command-line client

Platform Support

The platform folders follow Go's naming: darwin/amd64 (Intel macOS), darwin/arm64 (Apple Silicon), linux/amd64, linux/arm64. Each platform links only its own static library, so the final binary needs no rq-library at run time.

The libraries come from an rq-library release. lib/RQ_LIBRARY names it and lists the sha256 of its archives and of the installed files, so they can be checked against the release's SHA256SUMS. (Maintainers install a new release with a script in the development repository.)

Installation

To use this package in your Go project:

go get lumera.build/rq-go

Building needs cgo (a C toolchain). On macOS the libraries target macOS 11 or newer.

Then import it in your code:

import "lumera.build/rq-go"

Usage

Creating a Processor
package main

import (
    "log"
    "lumera.build/rq-go"
)

func main() {
    // Create a processor with default settings
    processor, err := raptorq.NewDefaultRaptorQProcessor()
    if err != nil {
        log.Fatalf("Failed to create processor: %v", err)
    }
    defer processor.Free() // Always free the processor when done

    // Or create with custom settings
    customProcessor, err := raptorq.NewRaptorQProcessor(
        65535,           // Symbol size (bytes)
        4,               // Redundancy factor
        4 * 1024,        // Max memory (MB) - 4GB
        2,               // Concurrency limit
    )
    // Use customProcessor...
}
Encoding a File
package main

import (
    "fmt"
    "log"
    "os"
    "lumera.build/rq-go"
)

func encodeExample() {
    processor, err := raptorq.NewDefaultRaptorQProcessor()
    if err != nil {
        log.Fatalf("Failed to create processor: %v", err)
    }
    defer processor.Free()

    // Get recommended block size for memory-efficient processing
    fileInfo, err := os.Stat("large_file.dat")
    if err != nil {
        log.Fatalf("Failed to get file info: %v", err)
    }
    blockSize := processor.GetRecommendedBlockSize(uint64(fileInfo.Size()))

    // Encode the file using the recommended block size
    result, err := processor.EncodeFile("large_file.dat", "symbols/", blockSize)
    if err != nil {
        log.Fatalf("Encoding failed: %v", err)
    }

    fmt.Printf("Encoded file with %d total symbols\n", result.TotalSymbolsCount)
    fmt.Printf("Layout file created at: %s\n", result.LayoutFilePath)
}
Decoding Symbols
package main

import (
    "fmt"
    "log"
    "lumera.build/rq-go"
)

func decodeExample() {
    processor, err := raptorq.NewDefaultRaptorQProcessor()
    if err != nil {
        log.Fatalf("Failed to create processor: %v", err)
    }
    defer processor.Free()

    // Decode symbols back to the original file
    err = processor.DecodeSymbols("symbols/", "recovered.dat", "symbols/_raptorq_layout.json")
    if err != nil {
        log.Fatalf("Decoding failed: %v", err)
    }

    fmt.Println("File successfully recovered")
}
Creating Metadata Only
package main

import (
    "fmt"
    "log"
    "lumera.build/rq-go"
)

func metadataExample() {
    processor, err := raptorq.NewDefaultRaptorQProcessor()
    if err != nil {
        log.Fatalf("Failed to create processor: %v", err)
    }
    defer processor.Free()

    // Generate metadata without creating symbols (for planning purposes)
    result, err := processor.CreateMetadata("large_file.dat", "layout.json", 1024*1024)
    if err != nil {
        log.Fatalf("Metadata creation failed: %v", err)
    }

    fmt.Printf("File would be encoded with %d total symbols\n", result.TotalSymbolsCount)
}

Block Processing and Memory Management

The RaptorQ library processes files in blocks to efficiently manage memory usage:

  1. Files are split into blocks of a specified size
  2. Each block is processed separately, minimizing peak memory usage
  3. The GetRecommendedBlockSize function calculates an optimal block size based on:
    • File size
    • Available memory (configured via maxMemoryMB)
    • Processing efficiency
    • Recovery capabilities

For large files, using the recommended block size is crucial to avoid excessive memory consumption.

Metadata File Format

During encoding, the library creates a metadata file (_raptorq_layout.json) in the output directory. This file contains:

  • Encoder parameters
  • Block information (size, offset, etc.)
  • Symbol identifiers

This metadata is essential for the decoding process, especially when files are split into multiple blocks.

{
  "blocks": [
    { 
      "block_id": integer, // block ID,
      "encoder_parameters": [/* 12 bytes */], // encoder parameters,
      "original_offset": integer, // offset of the block in the original file,
      "size": integer, // size of the block,
      "symbols": ["string", ...], // array of symbol hashes
      "hash": "block hash"  // hash of the block
    },
    ...
  ],
}

If input file is not split into blocks, the metadata file will contain only one block with ID 0.

Example Metadata File
{
  "blocks": [
    {
      "block_id": 0,
      "encoder_parameters": [
        0,
        0,
        25,
        240,
        160,
        0,
        195,
        80,
        1,
        0,
        1,
        8
      ],
      "original_offset": 0,
      "size": 1700000,
      "symbols": [
        "9yCaAXSexMsaWDP6pzK4wZ4w9Hqrr6QPjJZ86wJMGoq9",
        "3Q4MtczkeZzWbECcA8eUeMaQ14cGHF4PpgeYo33cMtYD",
        "G6okoLMA1wGtVZwieSykR9bvLSw49iwYZux2byJDrbDF",
        "AJ9fp8Ydqo1aaVHzjHowajJA4ELwfetpQAMUT47GZays"
      ],
      "hash": "9gD64LFuoQPYJoWBQmnG2TdPErWwni7Bhrpn6ae74rk7"
    },
    {
      "block_id": 1,
      "encoder_parameters": [
        0,
        0,
        25,
        240,
        160,
        0,
        195,
        80,
        1,
        0,
        1,
        8
      ],
      "original_offset": 1700000,
      "size": 1700000,
      "symbols": [
        "CxFNCbQhtWLzXwpGCE8L1m67WEV85zuTpTtYyRm6nDQF",
        "8NVZfQzFDsXwQgEbuNxzyo9D18da9qEHfDpou7mCzg72",
        "2hsAk5xWZCJ6d3xnnEaPu6TXsVwN6vfVhLDbKo7fsGVd",
        "96KaGntmMeqzL9uPxpKce2PMV9BiUXovMiDUBw1t3Mhz",
        "3kMQUazSrgfpxxkw3yY9zfh8amHXCeD7ZsmaDCu2szdB"
      ],
      "hash": "9LvSmppDKePbZnY6PLX8hyEY8gcskVJKwzmgn7zyPNyC"
    }
  ]
}

Configuration Options

The RaptorQ processor can be configured with several parameters:

Parameter Description Default
symbolSize Size of each symbol in bytes 65535 (64KB - 1 byte)
redundancyFactor Number of repair symbols per source symbol 4
maxMemoryMB Maximum memory usage limit in MB 16384 (16GB)
concurrencyLimit Maximum number of concurrent operations 4

License

This project is licensed under MIT License. See the LICENSE file for details.

Documentation

Overview

Package rq_go provides Go bindings for the RaptorQ erasure coding library. RaptorQ is a Forward Error Correction (FEC) code that allows for efficient recovery of data from partial information. This package enables encoding files into RaptorQ symbols and decoding them back, providing resilience against data loss.

Index

Constants

View Source
const (
	// DefaultSymbolSize is the default size of each symbol in bytes.
	// The symbol size affects encoding/decoding performance and memory usage.
	DefaultSymbolSize uint16 = 65535 // 64KB - 1 byte

	// DefaultRedundancyFactor determines how many repair symbols are generated.
	// Higher values provide better recovery capability but increase storage requirements.
	// A value of 4 means 4 repair symbols will be generated for each source symbol.
	DefaultRedundancyFactor uint8 = 4

	// DefaultMaxMemoryMB limits the maximum memory usage during encoding/decoding.
	// Default is 16GB, which is suitable for most modern systems.
	DefaultMaxMemoryMB uint64 = 16 * 1024

	// DefaultConcurrencyLimit controls the maximum number of concurrent operations.
	// This helps manage CPU usage and prevents system overload.
	DefaultConcurrencyLimit uint64 = 4

	// MaxMemoryMB_4GB provides a 4GB memory limit option for systems with less RAM.
	// Useful for embedded systems or when running in constrained environments.
	MaxMemoryMB_4GB uint64 = 4 * 1024
)

Default configuration values for the RaptorQ processor. These values match the defaults in the Rust library src/lib.rs and provide a good balance between performance and resource usage for most use cases.

Variables

This section is empty.

Functions

func GetVersion

func GetVersion() string

GetVersion returns the version of the underlying RaptorQ library.

This function queries the C library for its version string, which typically includes the version number and possibly build information. This can be useful for logging, debugging, or ensuring compatibility with specific library versions.

Returns:

  • string: The version string of the RaptorQ library. Returns "Unknown version" if the version information cannot be retrieved.

Example:

version := raptorq.GetVersion()
fmt.Printf("Using RaptorQ library version: %s\n", version)

Types

type Block

type Block struct {
	// BlockID is the unique identifier for this block.
	BlockID uint64 `json:"block_id"`

	// EncoderParameters contains parameters used by the RaptorQ algorithm for this block.
	// These are required for the decoding process.
	EncoderParameters []uint8 `json:"encoder_parameters"`

	// OriginalOffset is the offset of this block in the original file.
	OriginalOffset uint64 `json:"original_offset"`

	// Size is the size of this block in bytes.
	Size uint64 `json:"size"`

	// SymbolsCount is the total number of symbols in this block (source + repair).
	SymbolsCount uint32 `json:"symbols_count"`

	// SourceSymbolsCount is the number of source symbols in this block.
	// Source symbols contain the original data, while repair symbols provide redundancy.
	SourceSymbolsCount uint32 `json:"source_symbols_count"`

	// Hash is a hash of the block's data, used for integrity verification.
	Hash string `json:"hash"`
}

Block represents information about a processed data block during encoding. Files are split into blocks for processing, and each block has its own set of source and repair symbols. This structure contains the metadata needed to identify and decode a specific block.

type ProcessResult

type ProcessResult struct {
	// TotalSymbolsCount is the total number of symbols generated (source + repair).
	TotalSymbolsCount uint32 `json:"total_symbols_count"`

	// TotalRepairSymbols is the number of repair symbols generated.
	TotalRepairSymbols uint32 `json:"total_repair_symbols"`

	// SymbolsDirectory is the path to the directory containing the generated symbols.
	SymbolsDirectory string `json:"symbols_directory"`

	// Blocks contains information about each encoded block.
	// This field may be omitted in some responses.
	Blocks []Block `json:"blocks,omitempty"`

	// LayoutFilePath is the path to the file containing the layout information.
	// This file is required for decoding and contains metadata about the encoding process.
	LayoutFilePath string `json:"layout_file_path"`
}

ProcessResult holds information about the results of an encoding or metadata creation operation. It contains details about the generated symbols and the layout of the encoded data, which are necessary for the decoding process.

type ProcessorConfig

type ProcessorConfig struct {
	// SymbolSize defines the size of each symbol in bytes.
	// Larger symbols can improve throughput but increase memory usage.
	SymbolSize uint16 `json:"symbol_size"`

	// RedundancyFactor determines how many repair symbols are generated per source symbol.
	// Higher values provide better recovery capability but increase storage requirements.
	RedundancyFactor uint8 `json:"redundancy_factor"`

	// MaxMemoryMB limits the maximum memory usage during encoding/decoding in megabytes.
	// This prevents the process from consuming too much system memory.
	MaxMemoryMB uint64 `json:"max_memory_mb"`

	// ConcurrencyLimit controls the maximum number of concurrent operations.
	// This helps manage CPU usage and prevents system overload.
	ConcurrencyLimit uint64 `json:"concurrency_limit"`
}

ProcessorConfig holds configuration parameters for the RaptorQ processor. These settings control the behavior of the encoding and decoding processes, affecting performance, resource usage, and recovery capabilities.

type RaptorQProcessor

type RaptorQProcessor struct {
	// SessionID is the unique identifier for this processing session in the underlying C library.
	// It's used in all C function calls to identify the specific session.
	SessionID uintptr
}

RaptorQProcessor represents a RaptorQ processing session that handles encoding and decoding operations. Each processor maintains its own state and configuration, allowing for concurrent processing of multiple files with different settings. The processor must be freed when no longer needed to prevent memory leaks.

func NewDefaultRaptorQProcessor

func NewDefaultRaptorQProcessor() (*RaptorQProcessor, error)

NewDefaultRaptorQProcessor creates a new RaptorQ processor with default configuration.

This is a convenience function that creates a processor with the following default values:

  • Symbol size: 65535 bytes (64KB - 1 byte)
  • Redundancy factor: 4 (4 repair symbols per source symbol)
  • Max memory: 16GB
  • Concurrency limit: 4 threads

Returns:

  • *RaptorQProcessor: A new processor instance with default configuration if successful.
  • error: An error if the session initialization fails.

Example:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    log.Fatalf("Failed to create processor: %v", err)
}
defer processor.Free()

func NewRaptorQProcessor

func NewRaptorQProcessor(symbolSize uint16, redundancyFactor uint8, maxMemoryMB uint64, concurrencyLimit uint64) (*RaptorQProcessor, error)

NewRaptorQProcessor creates a new RaptorQ processor with the specified configuration.

This function initializes a new session with the underlying RaptorQ library and returns a processor that can be used for encoding and decoding operations.

Parameters:

  • symbolSize: Size of each symbol in bytes. Larger symbols can improve throughput but increase memory usage. Maximum value is 65535 (64KB - 1 byte).
  • redundancyFactor: Determines how many repair symbols are generated per source symbol. Higher values provide better recovery capability but increase storage requirements.
  • maxMemoryMB: Maximum memory usage limit in megabytes. This prevents the process from consuming too much system memory during encoding/decoding operations.
  • concurrencyLimit: Maximum number of concurrent operations. This helps manage CPU usage and prevents system overload.

Returns:

  • *RaptorQProcessor: A new processor instance if successful.
  • error: An error if the session initialization fails.

The returned processor must be freed when no longer needed by calling the Free() method to prevent memory leaks, although a finalizer is set to handle cleanup if Free() is not called.

func (*RaptorQProcessor) CreateMetadata

func (p *RaptorQProcessor) CreateMetadata(inputPath, layoutFile string, blockSize int) (*ProcessResult, error)

CreateMetadata creates metadata for RaptorQ encoding without writing symbol data.

This function analyzes the file at inputPath and generates the metadata needed for RaptorQ encoding, but doesn't actually create the encoded symbols. This is useful for planning purposes or for two-phase encoding processes where metadata generation and symbol creation are separate steps.

The function writes the layout information to the specified layout file, which contains details about how the file would be split into blocks and encoded.

Parameters:

  • inputPath: Path to the input file to analyze.
  • layoutFile: Path where the layout information will be written.
  • blockSize: Size of each block in bytes. If 0, a recommended block size will be used. Larger blocks can improve efficiency but require more memory during processing.

Returns:

  • *ProcessResult: Information about the metadata creation process, including details about how the file would be encoded (block count, symbol count, etc.).
  • error: An error if the metadata creation process fails. The error message will include details about the specific failure.

Possible error conditions include:

  • Session closed
  • File not found
  • I/O errors
  • Invalid paths
  • Memory limit exceeded
  • Concurrency limit reached
  • Invalid parameters

Example:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    return err
}
defer processor.Free()

// Generate metadata using 1MB blocks
result, err := processor.CreateMetadata("input.dat", "layout.json", 1024*1024)
if err != nil {
    return fmt.Errorf("metadata creation failed: %w", err)
}

fmt.Printf("File would be encoded with %d total symbols\n", result.TotalSymbolsCount)

func (*RaptorQProcessor) DecodeSymbols

func (p *RaptorQProcessor) DecodeSymbols(symbolsDir, outputPath, layoutPath string) error

DecodeSymbols decodes RaptorQ symbols back to the original file.

This function reads encoded symbols from the symbolsDir directory and uses the layout information from layoutPath to reconstruct the original file at outputPath. The RaptorQ algorithm can recover the original file even if some symbols are missing, as long as enough symbols are available.

Parameters:

  • symbolsDir: Directory containing the encoded symbols.
  • outputPath: Path where the reconstructed file will be written.
  • layoutPath: Path to the layout file containing metadata about the encoding. This file is created during the encoding process or by CreateMetadata.

Returns:

  • error: An error if the decoding process fails. The error message will include details about the specific failure. Returns nil on success.

Possible error conditions include:

  • Session closed
  • Empty parameters
  • File not found
  • I/O errors
  • Insufficient symbols for recovery
  • Memory limit exceeded
  • Concurrency limit reached
  • Invalid parameters

Example:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    return err
}
defer processor.Free()

// Decode symbols back to the original file
err = processor.DecodeSymbols("symbols/", "recovered.dat", "layout.json")
if err != nil {
    return fmt.Errorf("decoding failed: %w", err)
}

fmt.Println("File successfully recovered")

func (*RaptorQProcessor) EncodeFile

func (p *RaptorQProcessor) EncodeFile(inputPath, outputDir string, blockSize int) (*ProcessResult, error)

EncodeFile encodes a file using the RaptorQ erasure coding algorithm.

This function reads the file at inputPath, encodes it using RaptorQ, and writes the resulting symbols to the outputDir directory. The file is split into blocks of the specified size, and each block is encoded separately.

Parameters:

  • inputPath: Path to the input file to be encoded.
  • outputDir: Directory where the encoded symbols will be written.
  • blockSize: Size of each block in bytes. If 0, a recommended block size will be used. Larger blocks can improve efficiency but require more memory during processing.

Returns:

  • *ProcessResult: Information about the encoding process, including the total number of symbols generated, the path to the symbols directory, and metadata about each block.
  • error: An error if the encoding process fails. The error message will include details about the specific failure.

Possible error conditions include:

  • Session closed
  • File not found
  • I/O errors
  • Memory limit exceeded
  • Concurrency limit reached
  • Invalid parameters

Example:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    return err
}
defer processor.Free()

// Use 1MB blocks for encoding
result, err := processor.EncodeFile("input.dat", "symbols/", 1024*1024)
if err != nil {
    return fmt.Errorf("encoding failed: %w", err)
}

fmt.Printf("Encoded file with %d total symbols\n", result.TotalSymbolsCount)

func (*RaptorQProcessor) Free

func (p *RaptorQProcessor) Free() bool

Free manually frees the RaptorQ session and releases associated resources.

This method should be called when the processor is no longer needed to ensure that all resources are properly released. It's recommended to use defer immediately after creating a processor to ensure cleanup happens even if errors occur:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    return err
}
defer processor.Free()

Returns:

  • true: If the session was successfully freed.
  • false: If the session was already freed or if freeing failed.

Note that a finalizer is set to call this method automatically during garbage collection if it's not called manually, but explicit calls are preferred for deterministic cleanup.

func (*RaptorQProcessor) GetRecommendedBlockSize

func (p *RaptorQProcessor) GetRecommendedBlockSize(fileSize uint64) int

GetRecommendedBlockSize returns a recommended block size for a file of the given size.

This function calculates an optimal block size based on the file size and the processor's configuration. Using the recommended block size can improve encoding and decoding performance and efficiency.

The recommended block size balances several factors:

  • Memory usage during encoding/decoding
  • Processing speed
  • Recovery capabilities
  • Symbol count and management

Parameters:

  • fileSize: Size of the file in bytes.

Returns:

  • int: The recommended block size in bytes. Returns 0 if the session is closed.

Example:

processor, err := raptorq.NewDefaultRaptorQProcessor()
if err != nil {
    return err
}
defer processor.Free()

fileInfo, err := os.Stat("large_file.dat")
if err != nil {
    return err
}

blockSize := processor.GetRecommendedBlockSize(uint64(fileInfo.Size()))
fmt.Printf("Recommended block size: %d bytes\n", blockSize)

Source Files

  • raptorq.go

Jump to

Keyboard shortcuts

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