jsonstreamer

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: MIT Imports: 8 Imported by: 0

README

jsonstream

JSONstream is a powerful Go library designed to efficiently process large JSON array files through streaming, offering memory-efficient batch processing with comprehensive error handling, context-aware operations, and flexible output mechanisms.

Features

  • Generic Implementation: Works with any JSON-decodable type using Go generics
  • Context-Aware: Supports graceful cancellation and timeout handling
  • Streaming JSON Processing: Process large JSON arrays without loading the entire file into memory
  • Flexible Output Handling: Multiple output options:
    • Buffer channel for batch processing
    • Error channel for asynchronous error handling
    • Counter channel for progress tracking
    • Per-entry callback processing
    • Batch processing callbacks
  • Robust Error Handling:
    • Panic recovery with stack traces
    • Error thresholding to prevent infinite processing
    • Asynchronous error reporting
    • Detailed error context preservation
  • Configurable Processing:
    • Options-based configuration
    • Adjustable buffer size for batch processing
    • Ability to skip initial entries
    • Support for processing specific ranges of entries
    • Custom processor functions
  • Type Safety: Leverages Go generics for type-safe processing
  • Memory Efficient: Processes data in chunks to maintain low memory footprint
  • Recovery Mechanisms:
    • Tracks last valid entry offset
    • Supports skipping invalid entries
    • Maintains processing state

Install

go get github.com/thalesfsp/jsonstream

Error Handling

The library provides comprehensive error handling and reporting:

  • Panic Recovery:

    • Full stack trace capture
    • Safe error propagation
    • Resource cleanup
  • Error Context:

    • Original error message
    • File position information
    • Last successfully processed entry
    • Content of the problematic entry
    • Custom error fields and tags
  • Error Scenarios:

    • Context cancellation
    • Invalid JSON structure
    • Missing required fields
    • Type conversion errors
    • File access issues
    • Processing thresholds exceeded
    • Callback failures
  • Error Reporting:

    • Synchronous error returns
    • Asynchronous error channel
    • Error accumulation for batch reporting
    • Custom error types with rich context

Contributing

  1. Fork the repository
  2. Clone your fork
  3. Create a feature branch
  4. Make your changes
  5. Run tests
  6. Create a pull request

Documentation

Overview

Package jsonstreamer provides efficient streaming processing capabilities for large JSON array files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Read

func Read[T any](
	ctx context.Context,
	filename string,
	bufferSize int,
	options ...Func[T, T],
) error

Read is like ReadTo but with one defined type, setting default processor that returns the same document.

func ReadTo

func ReadTo[Source any, Target any](
	ctx context.Context,
	filename string,
	bufferSize int,
	options ...Func[Source, Target],
) (errP error)

ReadTo reads JSON array entries from a file, processes them, and outputs the results through channels or callback functions. It supports batch processing with buffering and entry skipping capabilities.

Parameters:

  • ctx: Context for cancellation control
  • filename: Path to the JSON file containing an array of Source type elements
  • bufferSize: Number of processed entries to accumulate before triggering output
  • options: Configuration options.

The function expects the input file to contain a valid JSON array. It processes entries one by one, allowing for efficient memory usage with large files. The function provides multiple output mechanisms that can be used independently or in combination:

  1. Buffer channel output (BufferCh): Processed entries are sent in batches
  2. Per-entry callback: Called immediately after processing each entry
  3. Per-buffer callback: Called when a buffer reaches bufferSize or at end of processing

Error Handling:

  • Implements panic recovery with stack trace capture
  • Returns custom errors for various failure scenarios
  • Maintains error threshold (maxErrorCount) to prevent infinite processing
  • Sends errors through ErrorCh for asynchronous handling
  • Accumulates errors for final error reporting

Recovery Mechanism:

  • Tracks the last valid entry offset for potential error recovery
  • Maintains processing state through currentOffset
  • Supports skipping invalid entries to continue processing

Context Support:

  • Honors context cancellation for graceful shutdown
  • Returns appropriate error when context is cancelled

The function implements graceful error handling and ensures resources are properly managed even in error conditions. It supports early termination through context cancellation and provides detailed error information for debugging purposes.

Flowchart:

```mermaid flowchart TD

Start([Start]) --> PanicRecover[Set up panic recovery]
PanicRecover --> ApplyOptions[Apply options]
ApplyOptions --> InputValidation{Check outputs}
InputValidation -->|Invalid| ReturnError1[Return Error: Missing outputs]
InputValidation -->|Valid| ValidateAmount{Validate amount}

ValidateAmount -->|Invalid| ReturnError2[Return Error: Invalid amount]
ValidateAmount -->|Valid| OpenFile[Open JSON file]

OpenFile -->|Error| ReturnError3[Return Error: Failed to open]
OpenFile -->|Success| ValidateArray[Validate JSON array structure]

ValidateArray -->|Invalid| ReturnError4[Return Error: Invalid format]
ValidateArray -->|Valid| ProcessLoop[Enter processing loop]

ProcessLoop --> CheckContext{Check context}
CheckContext -->|Cancelled| ReturnError5[Return Error: Context done]
CheckContext -->|Active| CheckErrors{Check error count}

CheckErrors -->|Too many| ReturnError6[Return Error: Too many errors]
CheckErrors -->|OK| CheckAmount{Check amount limit}

CheckAmount -->|Reached| HandleRemaining[Handle remaining buffer]
CheckAmount -->|Not reached| ReadEntry[Read JSON entry]

ReadEntry -->|Error| HandleDecodeError[Handle decode error]
ReadEntry -->|Success| CheckSkip{Skip entry?}

CheckSkip -->|Yes| UpdateOffset[Update last valid offset]
CheckSkip -->|No| ProcessDoc[Process document]

ProcessDoc -->|Error| SendError[Send to ErrorCh]
ProcessDoc -->|Success| UpdateCounter[Update CounterCh]

UpdateCounter --> HandleCallbacks[Handle callbacks]
SendError --> ProcessLoop

HandleCallbacks --> BufferCheck{Buffer full?}
BufferCheck -->|Yes| SendBuffer[Send buffer]
BufferCheck -->|No| ProcessLoop

SendBuffer --> ProcessLoop
HandleRemaining --> End([End])

HandleDecodeError --> ProcessLoop
UpdateOffset --> ProcessLoop

classDef error fill:#ff9999
class ReturnError1,ReturnError2,ReturnError3,ReturnError4,ReturnError5,ReturnError6 error

```.

Types

type CallbackPerBufferFunc added in v0.0.7

type CallbackPerBufferFunc[Target any] func([]Target) error

CallbackPerBufferFunc is a function applied to a buffer of JSON entries AFTER they are processed.

type CallbackPerEntryFunc added in v0.0.7

type CallbackPerEntryFunc[Target any] func(Target) error

CallbackPerEntryFunc is a function applied to each JSON entry AFTER it being processed.

type Errors added in v0.0.6

type Errors []error

Errors is a slice of errors.

func (Errors) Error added in v0.0.6

func (e Errors) Error() string

Error returns a string representation of the combined errors in the `Errors` slice, separated by commas. This method satisfies the `error` interface.

func (Errors) String added in v0.0.6

func (e Errors) String() string

Implement the stringer interface.

type Func added in v0.0.7

type Func[Source any, Target any] func(o *Options[Source, Target])

Func allows to set options.

func WithAmountOfEntries added in v0.0.7

func WithAmountOfEntries[Source any, Target any](amountOfEntries int) Func[Source, Target]

WithAmountOfEntries sets the amount of entries.

func WithBufferCh added in v0.0.7

func WithBufferCh[Source any, Target any](bufferCh chan<- []Target) Func[Source, Target]

WithBufferCh sets the buffer channel.

func WithCallbackPerBuffer added in v0.0.7

func WithCallbackPerBuffer[Source any, Target any](callback CallbackPerBufferFunc[Target]) Func[Source, Target]

WithCallbackPerBuffer sets the callback per buffer function.

func WithCallbackPerEntry added in v0.0.7

func WithCallbackPerEntry[Source any, Target any](callback CallbackPerEntryFunc[Target]) Func[Source, Target]

WithCallbackPerEntry sets the callback per entry function.

func WithCounterCh added in v0.0.8

func WithCounterCh[Source any, Target any](counterCh chan<- int) Func[Source, Target]

WithCounterCh sets the counter channel.

func WithErrorCh added in v0.0.7

func WithErrorCh[Source any, Target any](errorCh chan<- error) Func[Source, Target]

WithErrorCh sets the error channel.

func WithProcessor added in v0.0.7

func WithProcessor[Source any, Target any](processor ProcessorFunc[Source, Target]) Func[Source, Target]

WithProcessor sets the processor function.

func WithStartFrom added in v0.0.7

func WithStartFrom[Source any, Target any](startFrom int) Func[Source, Target]

WithStartFrom sets the start from.

type Options added in v0.0.7

type Options[Source any, Target any] struct {
	AmountOfEntries   int
	BufferCh          chan<- []Target
	CallbackPerBuffer CallbackPerBufferFunc[Target]
	CallbackPerEntry  CallbackPerEntryFunc[Target]
	CounterCh         chan<- int
	ErrorCh           chan<- error
	Processor         ProcessorFunc[Source, Target]
	StartFrom         int
}

Options contains the fields shared between request's options.

type ProcessorFunc added in v0.0.7

type ProcessorFunc[Source any, Target any] func(Source) (Target, error)

ProcessorFunc is a function that processes a JSON entry transforming it from the Source type to the Target type.

Jump to

Keyboard shortcuts

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