Files
golib/ioutils/fileDescriptor
nabbar 942068222c 2025-11 Improvement, Tests, Documentations, Bug Fix, Optimization
Global Repos / Workflow
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- UPDATE workflow: split old workflow into multiple files
- UPDATE .gitignore: added cluster.old.tar.gz and build artifacts
- UPDATE .golangci.yml: enhanced linter rules and disabled deprecated linters

[archive]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- FIX extract: recursive decompression for nested archives (e.g., .tar.gz handling)
- FIX extract: ZIP archive support now properly uses ReaderAt interface with seek reset
- ADD extract: proper symlink and hard link handling in archives
- UPDATE tar/writer: improved error handling and file mode preservation
- UPDATE zip/writer: enhanced validation and error messages
- UPDATE compress/interface: added support for additional compression formats
- UPDATE helper/compressor: fixed typo in error handling

[artifact]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE artifact: improved error handling and context management
- UPDATE client/interface: enhanced API with better type safety and context propagation
- UPDATE client/model: refactored for better maintainability
- UPDATE github: removed unused error codes, improved model validation
- UPDATE gitlab: enhanced API pagination and error handling
- UPDATE jfrog: improved artifactory API compatibility
- UPDATE s3aws: enhanced S3 bucket operations and error messages

[atomic]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE cast: improved type conversion with better error handling
- UPDATE interface: enhanced atomic operations with generics support
- UPDATE synmap: fixed race conditions in concurrent access patterns
- UPDATE value: improved atomic value operations with better memory ordering

[aws]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE bucket: enhanced ACL and CORS configuration with validation
- UPDATE configAws/models: improved credential handling and region configuration
- UPDATE configCustom/interface: added support for custom endpoints
- UPDATE http/request: improved retry logic and timeout handling
- UPDATE interface: enhanced AWS client with context propagation
- UPDATE model: refactored for AWS SDK v2 compatibility
- UPDATE multipart/interface: improved chunk handling for large uploads
- UPDATE pusher: optimized hash calculation and upload progress tracking
- UPDATE resolver: enhanced endpoint resolution with custom DNS
- DELETE test files: removed bucket_test.go, group_test.go, object_test.go, policy_test.go, role_test.go, user_test.go

[cache]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD context: context-aware cache lifecycle management
- UPDATE interface: complete rewrite with Go generics for type-safe key-value operations
- ADD item package: generic cache item with expiration tracking (interface and model)
- UPDATE model: refactored to use generics (Cache[K comparable, V any])
- REFACTOR: split item.go into modelAny.go for better code organization

[certificates]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE auth/encode: improved PEM encoding with better error messages
- UPDATE auth/interface: enhanced authentication certificate handling
- UPDATE ca: improved CA certificate generation and validation
- UPDATE certs: enhanced certificate configuration with SAN support
- UPDATE cipher: improved cipher suite selection and validation
- UPDATE curves: enhanced elliptic curve handling with additional curves
- ADD deprecated.go: marked deprecated TLS versions and cipher suites
- UPDATE interface: enhanced certificate interface with context support
- UPDATE model: improved certificate model with better validation
- UPDATE rootca: enhanced root CA pool management
- UPDATE tlsversion: added TLS 1.3 support with proper validation
- UPDATE tools: improved certificate utility functions

[cobra]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE completion: improved shell completion generation (bash, zsh, fish, powershell)
- UPDATE configure: enhanced configuration file handling
- UPDATE printError: improved error formatting with color support
- UPDATE interface: enhanced cobra interface with context support
- UPDATE model: improved cobra model with better validation

[config]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE components: improved component lifecycle management
- UPDATE const/const: improved constant definitions
- UPDATE context: enhanced context handling with better propagation
- UPDATE errors: improved error definitions
- UPDATE events: enhanced event management
- UPDATE manage: improved configuration management with validation
- UPDATE model: refactored config model
- UPDATE shell: enhanced shell integration for interactive configuration
- UPDATE types: improved component and componentList types

[console]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD buff.go: BuffPrintf function for colored output to io.Writer (moved from ioutils/multiplexer)
- DELETE color.go: removed legacy color file (consolidated functionality)
- UPDATE error: improved error definitions with better messages
- ADD interface: console interface for abstraction
- ADD model: console model for state management
- UPDATE padding: enhanced string padding with Unicode support
- UPDATE prompt: improved interactive prompt handling

[context]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- DELETE config.go: removed deprecated configuration (replaced by Config[T] interface)
- UPDATE context: improved context handling with better cancellation support
- UPDATE gin/interface: enhanced Gin context integration with type safety
- ADD helper: context helper functions for common operations
- ADD interface: generic Config[T comparable] interface for type-safe context storage
- ADD map: MapManage[T] interface for concurrent-safe map operations
- ADD model: thread-safe context model implementation with sync.Map

[database]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE gorm/config: improved database configuration
- UPDATE gorm/driver: enhanced database driver with better connection pooling
- UPDATE gorm/driver_darwin: macOS-specific database optimizations
- UPDATE gorm/interface: improved GORM interface with context support
- UPDATE gorm/model: refactored model for better maintainability
- UPDATE gorm/monitor: enhanced monitoring for database connections
- UPDATE kvtypes: improved types for key-value store (compare, driver, item, table)

[duration]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE big: enhanced big.Duration for large time spans with arithmetic operations
- UPDATE encode: improved marshaling for JSON, YAML, TOML, Text, CBOR
- UPDATE format: enhanced human-readable formatting (ns, μs, ms, s, m, h, d, w)
- UPDATE interface: improved duration interface with arithmetic methods
- UPDATE model: refactored Duration type
- UPDATE operation: enhanced arithmetic operations (Add, Sub, Mul, Div)
- UPDATE parse: improved parsing with multiple format support
- UPDATE truncate: enhanced truncation for rounding durations

[encoding]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE aes: improved AES encryption with reader/writer interfaces
- UPDATE hexa: enhanced hexadecimal encoding with better error handling
- UPDATE mux: improved multiplexer/demultiplexer for stream handling
- UPDATE randRead: enhanced random data generation
- UPDATE sha256 package: SHA-256 hashing with reader/writer interfaces

[errors]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD pool package: thread-safe error pool for collecting multiple errors with concurrent access
- UPDATE code: improved error code definition and lookup
- UPDATE errors: enhanced error creation with better stack trace
- UPDATE interface: improved error interface with more methods
- UPDATE mode: enhanced error mode handling (production vs development)
- UPDATE return: improved error return handling with context
- UPDATE trace: enhanced error tracing with file and line information

[file]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE bandwidth: improved bandwidth tracking with concurrency tests
- UPDATE perm: enhanced file permission handling with Unix/Windows support
- UPDATE perm/encode: improved marshaling for JSON, YAML, TOML
- UPDATE perm/format: enhanced permission formatting (e.g., "rwxr-xr-x")
- UPDATE perm/parse: improved parsing of permission strings and octal values
- UPDATE progress: enhanced progress tracking for file I/O operations
- UPDATE progress/io*: improved reader, writer, seeker, closer interfaces with progress callbacks

[ftpclient]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE config: improved FTP configuration with TLS support
- UPDATE errors: enhanced error definitions
- UPDATE interface: improved FTP client interface
- UPDATE model: refactored FTP client model

[httpcli]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE cli: improved HTTP client with retry logic and timeout handling
- UPDATE dns-mapper: enhanced DNS mapping for custom resolution
- UPDATE dns-mapper/config: improved DNS mapper configuration
- UPDATE dns-mapper/errors: enhanced error handling
- UPDATE dns-mapper/interface: improved DNS mapper interface
- UPDATE dns-mapper/transport: enhanced HTTP transport with DNS override
- UPDATE errors: improved error definitions
- UPDATE options: enhanced client options with context support

[httpserver]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE config: improved server configuration with TLS and middleware support
- UPDATE handler: enhanced request handler with better error handling
- UPDATE interface: improved server interface with context support and monitoring integration
- UPDATE model: refactored server model with better validation
- UPDATE monitor: enhanced monitoring integration with status tracking
- UPDATE pool: improved server pool management (config, interface, list, model)
- UPDATE run: enhanced server runtime with graceful shutdown
- UPDATE server: improved core server implementation with better lifecycle
- ADD testhelpers/certs.go: certificate generation utilities for testing
- UPDATE types: improved const, fields, and handler types

[ioutils]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE bufferReadCloser: improved buffered reader/writer with closer
- UPDATE fileDescriptor: enhanced file descriptor limit management (platform-specific for Linux/macOS/Windows)
- UPDATE ioprogress: improved progress tracking for I/O operations
- UPDATE iowrapper: enhanced I/O wrapper with custom interfaces
- UPDATE mapCloser: improved map of closers for resource management
- UPDATE maxstdio: enhanced C implementation for max stdio file descriptor retrieval
- DELETE multiplexer/model.go: removed legacy multiplexer (functionality moved to console/buff.go and retro/)
- UPDATE nopwritecloser: improved no-op write closer
- UPDATE tools: enhanced I/O utility functions

[ldap]
- UPDATE ldap: improved LDAP client with better connection handling and search operations

[logger]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE config: improved default values, file options, and syslog configuration
- UPDATE entry/interface: enhanced log entry with context support
- UPDATE fields: improved field handling with JSON cloning
- UPDATE gorm/interface: enhanced GORM logger with trace ID support
- UPDATE hashicorp/interface: improved HashiCorp logger integration
- FIX hookfile/system: use os.OpenRoot for secure file operations (prevents path traversal)
- FIX hookfile/system: fixed import path from libsrv "golib/server" to "golib/runner"
- ADD hookfile: IsRunning() method to track file hook state
- UPDATE hookstderr/interface: enhanced stderr hook with better buffering
- UPDATE hookstdout/interface: enhanced stdout hook with better buffering
- UPDATE hooksyslog: improved syslog integration with channel and priority handling
- ADD hookwriter package: generic io.Writer hook for custom output destinations
- UPDATE interface: enhanced logger interface with context propagation
- UPDATE level: improved log level handling and comparison
- UPDATE log: enhanced logging with better formatting
- UPDATE manage: improved logger lifecycle management
- UPDATE model: refactored logger model for better maintainability

[mail]
- UPDATE sender: improved mail sender with better MIME handling
- UPDATE interface: enhanced interface with monitoring support
- UPDATE monitor: added monitoring integration for mail operations

[monitor]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD status package: new subpackage for status management with Status type (KO, Warn, OK)
- ADD status/encode: marshaling support for JSON, YAML, TOML, Text, CBOR
- ADD status/format: human-readable status formatting
- ADD status/interface: Status type with Parse and String methods
- UPDATE encode: improved encoding with better error handling
- UPDATE error: enhanced error definitions
- UPDATE info: improved system info collection (CPU, mem, disk, network)
- UPDATE interface: enhanced monitor interface with status support and better component integration
- UPDATE metrics: improved metrics collection and export
- UPDATE middleware: enhanced monitoring middleware for HTTP
- UPDATE pool/interface: enhanced pool interface with better monitoring integration
- UPDATE pool/metrics: improved metrics collection in pool
- UPDATE pool/model: refactored pool model for better maintainability
- UPDATE pool/pool: enhanced pool implementation with better lifecycle
- UPDATE server: enhanced server monitoring with status tracking
- UPDATE types/monitor: improved monitor type definitions

[nats]
- UPDATE client: improved NATS client with better subscription handling
- UPDATE config: enhanced NATS configuration with cluster support
- UPDATE monitor: added monitoring integration for NATS operations
- UPDATE server: improved NATS server integration with monitoring

[network]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE bytes: improved byte size handling for network operations
- UPDATE number: enhanced number utilities for network data
- UPDATE protocol/encode: improved protocol encoding
- ADD protocol/format: protocol formatting utilities
- UPDATE protocol/interface: enhanced protocol interface
- UPDATE protocol/model: refactored protocol model

[password]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE password: improved password utilities with strength validation and secure generation

[pidcontroller]
- UPDATE interface: improved PID controller interface
- UPDATE model: enhanced PID controller model with better tuning parameters

[pprof]
- UPDATE tools: improved pprof utilities for profiling integration

[prometheus]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE bloom/bloom: improved bloom filter with better concurrency handling
- UPDATE bloom/collection: enhanced bloom filter collection operations
- UPDATE interface: enhanced prometheus interface with better type safety
- UPDATE metrics/interface: enhanced metrics interface with better registration
- UPDATE metrics/model: refactored metrics model for better maintainability
- UPDATE model: refactored prometheus model with better validation
- UPDATE pool: enhanced metric pool with concurrent access
- UPDATE pool/interface: enhanced pool interface
- UPDATE pool/model: refactored pool model
- UPDATE route: improved routing for metric endpoints
- UPDATE types: enhanced type definitions for metrics
- UPDATE webmetrics: improved existing metrics (requestBody, requestIPTotal, requestLatency, requestSlow, requestTotal, requestURITotal, responseBody)
- ADD webmetrics/activeConnections: gauge for tracking concurrent HTTP connections
- ADD webmetrics/requestErrors: counter for HTTP request errors
- ADD webmetrics/responseSizeByEndpoint: histogram for response size distribution by endpoint
- ADD webmetrics/statusCodeTotal: counter for HTTP status codes

[request]
- UPDATE interface: enhanced request interface with better type safety
- UPDATE model: refactored request model for better maintainability
- UPDATE options: improved request options with better validation
- UPDATE url: enhanced URL handling with better parsing

[retro]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE encoding: improved encoding utilities with better format support
- UPDATE format: enhanced formatting functions for retro compatibility
- UPDATE model: refactored retro model with better validation
- UPDATE utils: improved utility functions for version handling
- UPDATE version: enhanced version utilities for retro compatibility

[router]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE auth/interface: enhanced authentication interface with better validation
- UPDATE auth/model: improved authentication model
- UPDATE authheader/interface: enhanced authentication header interface
- UPDATE default: improved default router configuration
- UPDATE error: enhanced error definitions for router
- UPDATE header/config: improved header configuration
- UPDATE header/interface: enhanced header interface
- UPDATE header/model: refactored header model
- UPDATE interface: improved router interface with better type safety
- UPDATE middleware: improved router middleware with better error handling
- UPDATE model: refactored router model for better maintainability
- UPDATE router: enhanced core router implementation
- UPDATE tools: enhanced router utilities for route registration

[runner]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE package: move package for lifecycle management of long-running services (moved from server/runner)
- ADD interface: Runner interface with Start, Stop, Restart, IsRunning, and Uptime methods
- ADD startStop package: service lifecycle with blocking start and graceful stop (interface, model, comprehensive tests)
- ADD ticker package: periodic task execution at regular intervals (interface, model, comprehensive tests)
- ADD tests: concurrency, construction, errors, lifecycle, and uptime tests for both startStop and ticker
- ADD tools: RecoveryCaller for panic recovery in goroutines

[semaphore]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- FIX bar/bar: Dec method now properly decrements (was calling Inc64, now calls Dec64 with negative value)
- UPDATE bar: improved progress bar with better MPB integration
- UPDATE bar/context: enhanced context handling for cancellation
- UPDATE bar/interface: added methods for Total() and better progress tracking
- UPDATE bar/model: improved model with atomic operations
- UPDATE bar tests: enhanced bar_operations_test, edge_cases_test, integration_test, and semaphore_test
- UPDATE context: enhanced context propagation
- UPDATE interface: improved semaphore interface with weighted operations
- UPDATE model: refactored model for better thread safety
- UPDATE progress: enhanced progress tracking with multiple bars
- UPDATE sem/interface: added IsRunning() method for state tracking
- UPDATE sem/ulimit: improved ulimit handling for file descriptors
- UPDATE sem/weighted: enhanced weighted semaphore operations
- UPDATE types: improved type definitions for bar, progress, and semaphore

[server]
- REFACTOR: moved runner subpackage to root-level runner package
- DELETE: empty package after moved runner subpackage

[shell]
- UPDATE goprompt: improved interactive prompt handling with better input validation

[size]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD arithmetic.go: NEW file with arithmetic operations (Add, Sub, Mul, Div with overflow detection)
- UPDATE encode: improved marshaling for JSON, YAML, TOML, Text, CBOR
- UPDATE format: enhanced human-readable formatting (B, KB, MB, GB, TB, PB, EB)
- UPDATE interface: added arithmetic methods (Mul, MulErr, Div, DivErr, Add, AddErr, Sub, SubErr)
- UPDATE model: refactored Size type with better validation
- UPDATE parse: improved parsing with unit detection (IEC and SI standards)

[smtp]
- UPDATE client: improved SMTP client with better error handling
- UPDATE config: enhanced configuration with validation
- UPDATE config/error: improved error definitions
- UPDATE config/interface: enhanced interface with context support
- UPDATE config/model: refactored model for better maintainability
- UPDATE interface: improved SMTP interface with monitoring support
- UPDATE monitor: added monitoring integration for SMTP operations
- DELETE network/network.go: removed legacy network handling (consolidated into client)
- UPDATE tlsmode/tls: enhanced TLS mode handling (None, TLS, StartTLS)
- UPDATE types/interface: improved type interface

[socket]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- ADD client/interface_darwin: macOS-specific socket client options
- UPDATE client/interface_linux: platform-specific socket options for Linux
- UPDATE client/interface_other: platform-specific socket options for other platforms
- UPDATE client/tcp/error: improved TCP client error handling
- UPDATE client/tcp/interface: enhanced TCP client interface
- UPDATE client/tcp/model: improved TCP client model
- UPDATE client/udp/error: improved UDP client error handling
- UPDATE client/udp/interface: enhanced UDP client interface
- UPDATE client/udp/model: improved UDP client model
- UPDATE client/unix/error: improved Unix socket client error handling
- UPDATE client/unix/ignore: enhanced ignore functionality
- UPDATE client/unix/interface: enhanced Unix socket client interface
- UPDATE client/unix/model: improved Unix socket client model
- UPDATE client/unixgram/error: improved Unix datagram client error handling
- UPDATE client/unixgram/ignore: enhanced ignore functionality
- UPDATE client/unixgram/interface: enhanced Unix datagram client interface
- UPDATE client/unixgram/model: improved Unix datagram client model
- UPDATE config/client: improved client configuration
- UPDATE config/server: improved server configuration
- DELETE delim: moved legacy delimiter to I/O package
- UPDATE interface: improved socket interface
- UPDATE io: enhanced I/O operations
- DELETE multi: moved legacy multi to I/O package
- ADD server/interface_darwin: macOS-specific socket server options
- UPDATE server/interface_linux: platform-specific server options for Linux
- UPDATE server/interface_other: platform-specific server options for other platforms
- UPDATE server/tcp/error: improved TCP server error handling
- UPDATE server/tcp/interface: enhanced TCP server interface
- UPDATE server/tcp/listener: improved TCP server listener
- UPDATE server/tcp/model: improved TCP server model
- UPDATE server/udp/error: improved UDP server error handling
- UPDATE server/udp/interface: enhanced UDP server interface
- UPDATE server/udp/listener: improved UDP server listener
- UPDATE server/udp/model: improved UDP server model
- UPDATE server/unix/error: improved Unix socket server error handling
- UPDATE server/unix/ignore: enhanced ignore functionality
- UPDATE server/unix/interface: enhanced Unix socket server interface
- UPDATE server/unix/listener: improved Unix socket server listener
- UPDATE server/unix/model: improved Unix socket server model
- UPDATE server/unixgram/error: improved Unix datagram server error handling
- UPDATE server/unixgram/ignore: enhanced ignore functionality
- UPDATE server/unixgram/interface: enhanced Unix datagram server interface
- UPDATE server/unixgram/listener: improved Unix datagram server listener
- UPDATE server/unixgram/model: improved Unix datagram server model

[static]
- UPDATE interface: improved static interface with monitoring support
- UPDATE model: refactored static model
- UPDATE monitor: added monitoring integration for static file operations

[status]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE cache: improved status cache with better synchronization
- UPDATE config: improved status configuration
- UPDATE control/encode: improved control encoding
- UPDATE control/interface: enhanced control interface with status tracking
- UPDATE control/model: refactored control model
- UPDATE encode: improved status encoding
- UPDATE error: enhanced error definitions for status
- UPDATE info: improved status info handling
- UPDATE interface: enhanced status interface
- UPDATE listmandatory/interface: improved list mandatory interface
- UPDATE listmandatory/model: refactored list mandatory model
- UPDATE mandatory/interface: enhanced mandatory interface
- UPDATE mandatory/model: refactored mandatory model
- UPDATE model: refactored status model
- UPDATE pool: improved status pool
- UPDATE route: enhanced status route handling

[test]
- DELETE: all manual tests are or will be replaced by proper automated test suites in respective packages

[version]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE error: improved error definitions for version
- UPDATE license: enhanced license handling
- UPDATE version: improved version utilities

[viper]
- ADD/UPDATE documentation: comprehensive documentation with monitoring patterns
- ADD/UPDATE tests: enhanced benchmark, config, encoding, example, integration, lifecycle, metrics, security, transitions
- UPDATE interface: enhanced viper interface with context support
- UPDATE model: refactored viper model for better maintainability
2025-11-15 21:09:32 +01:00
..

FileDescriptor Package

License: MIT Go Version Coverage

Cross-platform file descriptor limit management for Go applications with automatic platform detection and safe limit modification.


Table of Contents


Overview

This package provides a unified, cross-platform API for managing file descriptor limits (the maximum number of open files or I/O resources) in Go applications. It abstracts platform differences between Unix/Linux, macOS, and Windows, offering a simple interface for both querying current limits and safely increasing them when needed.

Design Philosophy

  1. Platform Abstraction: Single API works across Unix/Linux, macOS, and Windows
  2. Safety First: Never decreases limits, respects system constraints
  3. Graceful Degradation: Handles permission errors without panic
  4. Minimal Interface: One function does everything
  5. Zero Dependencies: Only standard library and platform-specific syscalls

Key Features

  • Cross-Platform: Unified API for Unix/Linux, macOS, and Windows
  • Simple Interface: Single function call for all operations
  • Safe Operations: Respects system hard limits, never decreases existing limits
  • Permission Aware: Gracefully handles privilege requirements
  • Zero Overhead: No runtime cost after initial setup
  • Production Ready: 85.7% test coverage, 23 specs
  • Well Documented: Comprehensive GoDoc and examples

Installation

go get github.com/nabbar/golib/ioutils/fileDescriptor

Architecture

Package Structure

The package uses build tags to provide platform-specific implementations:

fileDescriptor/
├── fileDescriptor.go       # Public API and package documentation
├── fileDescriptor_ok.go    # Unix/Linux/macOS implementation (!windows)
└── fileDescriptor_ko.go    # Windows implementation (windows)

Platform-Specific Implementations

┌─────────────────────────────────────────────────┐
│        SystemFileDescriptor(newValue)           │
│              Public API                         │
└──────────────────┬──────────────────────────────┘
                   │
         ┌─────────▼─────────┐
         │  Build Tag Check  │
         └─────────┬─────────┘
                   │
       ┌───────────┴───────────┐
       │                       │
┌──────▼──────┐        ┌──────▼──────┐
│Unix/Linux   │        │  Windows    │
│  macOS      │        │             │
├─────────────┤        ├─────────────┤
│syscall.     │        │maxstdio.    │
│ Getrlimit   │        │ GetMaxStdio │
│ Setrlimit   │        │ SetMaxStdio │
│RLIMIT_NOFILE│        │  (max 8192) │
└─────────────┘        └─────────────┘

Operation Flow

User calls SystemFileDescriptor(newValue)
       ↓
1. Query current limits (platform-specific)
       ↓
2. newValue <= 0 or newValue <= current?
   ├─ Yes → Return current limits (no modification)
   └─ No  → Continue to step 3
       ↓
3. newValue > hard limit?
   ├─ Unix: May require root privileges
   └─ Windows: Cap at 8192
       ↓
4. Attempt to increase limit (syscall/maxstdio)
       ↓
5. Return new limits or error

Platform Behavior Comparison

Aspect Unix/Linux/macOS Windows
Implementation syscall.Rlimit maxstdio (C runtime)
Default Limit 1024-4096 512
Hard Limit 4096-unlimited 8192 (fixed)
Privilege Required Root for hard limit increase None (within 8192)
Decrease Allowed No No
Thread Safety Yes (kernel-level) Yes (CRT-level)

Quick Start

Query Current Limits

package main

import (
    "fmt"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func main() {
    // Query without modification (newValue = 0)
    current, max, err := fileDescriptor.SystemFileDescriptor(0)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Current (soft) limit: %d\n", current)
    fmt.Printf("Maximum (hard) limit: %d\n", max)
    // Output example (Linux):
    // Current (soft) limit: 1024
    // Maximum (hard) limit: 65536
}

Increase Limit

package main

import (
    "fmt"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func main() {
    // Attempt to increase to 4096
    newLimit := 4096
    current, max, err := fileDescriptor.SystemFileDescriptor(newLimit)
    if err != nil {
        log.Fatalf("Cannot increase limit: %v (may need elevated privileges)", err)
    }
    
    fmt.Printf("Limit increased to: %d (max: %d)\n", current, max)
}

Initialize Server with Required Limits

package main

import (
    "fmt"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

const RequiredFDs = 8192

func main() {
    // Ensure minimum file descriptors at startup
    current, max, err := fileDescriptor.SystemFileDescriptor(RequiredFDs)
    if err != nil {
        log.Fatalf("Cannot set required FD limit: %v", err)
    }
    
    if current < RequiredFDs {
        log.Fatalf("Insufficient FDs: have %d, need %d (max: %d)", current, RequiredFDs, max)
    }
    
    fmt.Printf("Server starting with %d file descriptors available\n", current)
    // Start server...
}

Performance

Operation Metrics

The package adds minimal overhead to your application:

Operation Time Overhead Notes
Query (newValue=0) ~500 ns Negligible Single syscall
Increase limit ~1-5 µs One-time cost Syscall + validation
Subsequent calls 0 Zero overhead Limits persist process-wide

Measured on Linux AMD64, Go 1.21

Performance Characteristics

  • No Runtime Overhead: After setting limits, zero performance cost
  • One-Time Setup: Typically called once during application startup
  • Fast Queries: Sub-microsecond limit queries
  • Cached by OS: System maintains limits, no memory overhead
  • Thread-Safe: Kernel-level synchronization (no app-level locks needed)

Benchmark Results

BenchmarkQuery-8          2000000    537 ns/op     0 B/op    0 allocs/op
BenchmarkIncrease-8       500000     3421 ns/op    0 B/op    0 allocs/op

Memory Usage

  • Package Size: ~10 KB compiled
  • Runtime Memory: 0 bytes (no state maintained)
  • Allocations: 0 per call
  • System Memory: Managed by OS kernel

Use Cases

This package is essential for applications that need to manage many concurrent I/O operations:

High-Traffic Web Servers

Web servers handling thousands of concurrent connections:

package main

import (
    "log"
    "net/http"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func main() {
    // Increase limit for handling many concurrent connections
    const ServerFDs = 16384
    current, _, err := fileDescriptor.SystemFileDescriptor(ServerFDs)
    if err != nil || current < ServerFDs {
        log.Fatalf("Cannot set required FD limit for web server")
    }
    
    log.Printf("Server starting with %d file descriptors\n", current)
    http.ListenAndServe(":8080", nil)
}

Why: Each HTTP connection requires a file descriptor. High-traffic servers need many FDs.

Database Connection Pools

Applications with large database connection pools:

package main

import (
    "database/sql"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func initDatabase() (*sql.DB, error) {
    // Reserve FDs for DB connections + overhead
    poolSize := 100
    requiredFDs := poolSize + 500 // Pool + logs + other files
    
    current, _, err := fileDescriptor.SystemFileDescriptor(requiredFDs)
    if err != nil {
        return nil, err
    }
    
    if current < requiredFDs {
        log.Printf("Warning: Only %d FDs available, may limit connections", current)
    }
    
    db, _ := sql.Open("postgres", "connstring")
    db.SetMaxOpenConns(min(poolSize, current-500))
    return db, nil
}

Why: Each database connection consumes a file descriptor. Large pools need adequate limits.

File Processing Pipelines

Batch processing many files simultaneously:

package main

import (
    "fmt"
    "os"
    "sync"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func processFiles(files []string) error {
    // Check if we have enough FDs for parallel processing
    required := len(files) + 100 // Files + safety margin
    current, _, _ := fileDescriptor.SystemFileDescriptor(required)
    
    if current < required {
        return fmt.Errorf("need %d FDs to process %d files, have %d", 
            required, len(files), current)
    }
    
    var wg sync.WaitGroup
    for _, path := range files {
        wg.Add(1)
        go func(p string) {
            defer wg.Done()
            f, _ := os.Open(p)
            defer f.Close()
            // Process file...
        }(path)
    }
    wg.Wait()
    return nil
}

Why: Opening many files concurrently requires sufficient file descriptor limit.

Microservices with Many Connections

Services connecting to multiple backends:

package main

import (
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

type Microservice struct {
    databases []Database
    caches    []Cache
    queues    []Queue
}

func (m *Microservice) Initialize() error {
    // Calculate total FDs needed
    totalConnections := 
        len(m.databases) * 20 +  // DB pools
        len(m.caches) * 10 +     // Cache connections
        len(m.queues) * 5 +      // Queue connections
        1000                     // Incoming HTTP requests
    
    current, max, err := fileDescriptor.SystemFileDescriptor(totalConnections)
    if err != nil {
        return err
    }
    
    log.Printf("Microservice initialized with %d/%d FDs\n", current, max)
    return nil
}

Why: Microservices often maintain many persistent connections to various services.

Network Proxies and Load Balancers

Proxies routing traffic between clients and servers:

package main

import (
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func startProxy() error {
    // Each proxied connection uses 2 FDs (client + backend)
    maxConnections := 10000
    requiredFDs := maxConnections * 2 + 1000 // Connections + overhead
    
    current, max, err := fileDescriptor.SystemFileDescriptor(requiredFDs)
    if err != nil {
        log.Printf("Warning: cannot increase FD limit: %v", err)
    }
    
    actualMax := min(current/2-500, maxConnections)
    log.Printf("Proxy starting: max %d concurrent connections (FDs: %d/%d)\n", 
        actualMax, current, max)
    
    // Start proxy with actualMax limit...
    return nil
}

Why: Proxies double file descriptor usage (one FD for client, one for backend).


API Reference

SystemFileDescriptor

func SystemFileDescriptor(newValue int) (current int, max int, err error)

The single function that does everything - queries and optionally modifies file descriptor limits.

Parameters:

  • newValue int: Desired new limit
    • <= 0: Query mode (no modification)
    • > 0 and <= current: Query mode (already at or above requested value)
    • > current: Attempt to increase to newValue

Returns:

  • current int: Current (soft) file descriptor limit
  • max int: Maximum (hard) file descriptor limit
  • err error: Error if the operation fails (nil on success)

Behavior Summary:

newValue Action Privileges Required
<= 0 Query only None
<= current Query only None
> current && <= hard Increase soft limit Usually none (Unix) / None (Windows)
> hard Increase hard limit Root/admin (Unix) / Capped at 8192 (Windows)

Error Conditions:

  • Permission Denied: Attempting to increase beyond allowed limit without privileges
  • System Error: Underlying syscall failure (rare)
  • Platform Limit: On Windows, automatically caps at 8192

Examples:

// Query current limits
current, max, _ := fileDescriptor.SystemFileDescriptor(0)

// Increase to 4096 (may fail without privileges)
current, max, err := fileDescriptor.SystemFileDescriptor(4096)
if err != nil {
    log.Printf("Cannot increase: %v", err)
}

// Safe increase with fallback
desired := 16384
current, max, err := fileDescriptor.SystemFileDescriptor(desired)
if err != nil || current < desired {
    log.Printf("Using %d FDs instead of %d", current, desired)
}

Usage Examples

Example 1: Check Before Opening Many Files

package main

import (
    "fmt"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func main() {
    filesNeeded := 2000
    
    current, max, err := fileDescriptor.SystemFileDescriptor(0)
    if err != nil {
        log.Fatal(err)
    }
    
    if current < filesNeeded {
        fmt.Printf("Need %d file descriptors, but only %d available\n", filesNeeded, current)
        fmt.Printf("Attempting to increase limit...\n")
        
        newCurrent, newMax, err := fileDescriptor.SystemFileDescriptor(filesNeeded)
        if err != nil {
            log.Fatalf("Cannot increase limit: %v (may need elevated privileges)", err)
        }
        
        fmt.Printf("Successfully increased limit to %d (max: %d)\n", newCurrent, newMax)
    } else {
        fmt.Printf("Current limit (%d) is sufficient\n", current)
    }
}

Example 2: Initialize High-Performance Server

package main

import (
    "fmt"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

const (
    MinRequiredFDs = 4096
    PreferredFDs   = 65536
)

func initializeServer() error {
    current, max, err := fileDescriptor.SystemFileDescriptor(0)
    if err != nil {
        return fmt.Errorf("cannot check file descriptor limits: %w", err)
    }
    
    fmt.Printf("Initial limits - Current: %d, Max: %d\n", current, max)
    
    // Check minimum requirement
    if current < MinRequiredFDs {
        return fmt.Errorf("insufficient file descriptors: have %d, need at least %d", current, MinRequiredFDs)
    }
    
    // Try to set preferred limit
    if current < PreferredFDs && max >= PreferredFDs {
        fmt.Printf("Attempting to increase limit to %d...\n", PreferredFDs)
        
        newCurrent, newMax, err := fileDescriptor.SystemFileDescriptor(PreferredFDs)
        if err != nil {
            log.Printf("Warning: Could not set preferred limit: %v", err)
        } else {
            fmt.Printf("Increased limits - Current: %d, Max: %d\n", newCurrent, newMax)
        }
    }
    
    return nil
}

func main() {
    if err := initializeServer(); err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Server initialized successfully")
}

Example 3: Safe Limit Increase with Fallback

package main

import (
    "fmt"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func ensureMinimumFDs(required int) (int, error) {
    current, max, err := fileDescriptor.SystemFileDescriptor(0)
    if err != nil {
        return 0, err
    }
    
    if current >= required {
        return current, nil
    }
    
    // Try to increase to required
    newCurrent, _, err := fileDescriptor.SystemFileDescriptor(required)
    if err != nil {
        // If we can't increase, check if max is sufficient
        if max >= required {
            return 0, fmt.Errorf("current limit is %d but need %d (max is %d, may need elevated privileges)", current, required, max)
        }
        return 0, fmt.Errorf("system maximum (%d) is below required (%d)", max, required)
    }
    
    return newCurrent, nil
}

func main() {
    limit, err := ensureMinimumFDs(2048)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("File descriptor limit ensured: %d\n", limit)
}

Example 4: Graceful Degradation

package main

import (
    "fmt"
    "log"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

type ServerConfig struct {
    TargetFDs      int
    MinimumFDs     int
    MaxConnections int
}

func configureServer(cfg *ServerConfig) error {
    current, _, err := fileDescriptor.SystemFileDescriptor(0)
    if err != nil {
        return err
    }
    
    // Try to reach target
    if current < cfg.TargetFDs {
        newCurrent, _, err := fileDescriptor.SystemFileDescriptor(cfg.TargetFDs)
        if err == nil {
            current = newCurrent
            log.Printf("Increased FD limit to %d", current)
        } else {
            log.Printf("Could not increase to target %d: %v", cfg.TargetFDs, err)
        }
    }
    
    // Check minimum
    if current < cfg.MinimumFDs {
        return fmt.Errorf("insufficient file descriptors: %d (need at least %d)", current, cfg.MinimumFDs)
    }
    
    // Adjust max connections based on available FDs
    // Reserve some FDs for other purposes (logs, databases, etc.)
    availableForConns := current - 100
    if availableForConns < cfg.MaxConnections {
        log.Printf("Reducing max connections from %d to %d due to FD limits", cfg.MaxConnections, availableForConns)
        cfg.MaxConnections = availableForConns
    }
    
    log.Printf("Server configured with %d FDs, max %d connections", current, cfg.MaxConnections)
    return nil
}

func main() {
    cfg := &ServerConfig{
        TargetFDs:      8192,
        MinimumFDs:     1024,
        MaxConnections: 5000,
    }
    
    if err := configureServer(cfg); err != nil {
        log.Fatal(err)
    }
}

Example 5: Monitoring and Alerting

package main

import (
    "fmt"
    "time"
    "github.com/nabbar/golib/ioutils/fileDescriptor"
)

func monitorFileDescriptors(interval time.Duration, warningThreshold float64) {
    ticker := time.NewTicker(interval)
    defer ticker.Stop()
    
    for range ticker.C {
        current, max, err := fileDescriptor.SystemFileDescriptor(0)
        if err != nil {
            fmt.Printf("Error checking FD limits: %v\n", err)
            continue
        }
        
        // Calculate usage percentage (rough estimate)
        // Note: current is the limit, not the actual usage
        usage := float64(current) / float64(max)
        
        fmt.Printf("FD Limits - Current: %d, Max: %d (%.1f%% of max)\n", current, max, usage*100)
        
        if usage >= warningThreshold {
            fmt.Printf("WARNING: File descriptor limit is high (%.1f%%)\n", usage*100)
            // Send alert, log, etc.
        }
    }
}

func main() {
    fmt.Println("Monitoring file descriptor limits...")
    monitorFileDescriptors(30*time.Second, 0.8) // Check every 30s, warn at 80%
}

Platform Support

Unix/Linux/macOS

Implementation: syscall.Getrlimit / syscall.Setrlimit with RLIMIT_NOFILE

Typical Defaults:

  • Soft limit: 1024-4096 (distribution-dependent)
  • Hard limit: 4096-unlimited (often 65536 or unlimited)

Privilege Requirements:

  • Increase soft limit (≤ hard): No privileges needed
  • Increase hard limit: Root (superuser) privileges required

System Commands:

# Check current limits
ulimit -n           # Soft limit (current)
ulimit -Hn          # Hard limit (maximum)

# Temporarily increase (current shell only)
ulimit -n 8192

# View process limits
cat /proc/<pid>/limits | grep "open files"

# Check system-wide max
cat /proc/sys/fs/file-max

Persistent Configuration:

Edit /etc/security/limits.conf (requires root):

*     soft  nofile  4096
*     hard  nofile  65536
root  soft  nofile  8192
root  hard  nofile  unlimited

Distribution-Specific:

  • Ubuntu/Debian: Also check /etc/pam.d/common-session
  • RHEL/CentOS: Also check /etc/security/limits.d/*.conf
  • systemd services: Set LimitNOFILE= in service unit file

Windows

Implementation: maxstdio.GetMaxStdio / maxstdio.SetMaxStdio (C runtime)

Limits:

  • Default: 512 file descriptors
  • Maximum: 8192 file descriptors (hard limit, cannot exceed)
  • No privileges required to increase (within 8192)

Important Differences:

  • Windows limits are per-process C runtime limits, not OS-level kernel limits
  • Much lower than Unix systems (8192 vs potentially unlimited)
  • Applies to C stdio functions and file handles opened with them
  • Go's os.Open uses Windows API directly, but may still be affected

Registry (advanced):

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems

Modify "Windows" value (requires reboot, not recommended)

Recommendation: Design applications to work within 8192 FD limit on Windows.


Testing

The package has 85.7% test coverage with 23 comprehensive specs using Ginkgo v2 and Gomega.

Run Tests

# Standard go test
go test -v -cover .

# With Ginkgo CLI (recommended)
go install github.com/onsi/ginkgo/v2/ginkgo@latest
ginkgo -v -cover

Test Statistics

Metric Value
Total Specs 23
Passed 20
Skipped 3 (permission/state dependent)
Coverage 85.7%
Execution Time ~2ms

Coverage Breakdown

Component File Coverage Notes
Public API fileDescriptor.go 100.0% Fully tested
Unix impl fileDescriptor_ok.go 89.5% Some branches need root
Windows impl fileDescriptor_ko.go N/A Platform-specific

Why 3 tests are skipped: Some tests require specific system states (already at max) or elevated privileges. This is expected and normal.

See TESTING.md for detailed testing documentation.


Best Practices

1. Initialize Early in main()

Set limits before creating connections or opening files:

func main() {
    // First: Set file descriptor limits
    if _, _, err := fileDescriptor.SystemFileDescriptor(8192); err != nil {
        log.Fatalf("Cannot set FD limit: %v", err)
    }
    
    // Then: Start application
    startServer()
}

2. Handle Permission Errors Gracefully

Don't fail hard if limit increase is denied:

current, max, err := fileDescriptor.SystemFileDescriptor(16384)
if err != nil {
    log.Printf("Warning: Cannot increase FD limit: %v", err)
    log.Printf("Continuing with %d FDs (max: %d)", current, max)
}

3. Reserve Safety Margin

Don't use all available FDs:

current, _, _ := fileDescriptor.SystemFileDescriptor(0)
maxConnections := current - 200  // Reserve for logs, DB, etc.

4. Check Before Requiring

Verify limits meet requirements before proceeding:

const RequiredFDs = 4096

current, _, _ := fileDescriptor.SystemFileDescriptor(RequiredFDs)
if current < RequiredFDs {
    return fmt.Errorf("insufficient FDs: need %d, have %d", RequiredFDs, current)
}

5. Platform-Aware Limits

Adjust expectations based on platform:

import "runtime"

targetFDs := 65536
if runtime.GOOS == "windows" {
    targetFDs = 8192  // Windows maximum
}
fileDescriptor.SystemFileDescriptor(targetFDs)

6. Document Requirements

Clearly state FD requirements in documentation:

// Server requires at least 4096 file descriptors.
// Recommended: 16384 for high-traffic deployments.
// Run with: ulimit -n 16384 && ./server (Unix)
const (
    MinimumFDs    = 4096
    RecommendedFDs = 16384
)

7. Log Limit Changes

Track limit modifications for debugging:

original, _, _ := fileDescriptor.SystemFileDescriptor(0)
current, max, err := fileDescriptor.SystemFileDescriptor(8192)
if err == nil && current != original {
    log.Printf("Increased FD limit: %d → %d (max: %d)", original, current, max)
}

Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass tests: go test ./...
  • Maintain test coverage (≥85%)
  • Follow existing code style and patterns
  • Add GoDoc comments for all public elements

Documentation

  • Update README.md for new features
  • Add practical examples for common use cases
  • Keep TESTING.md synchronized with test changes
  • Use clear, concise English

Testing

  • Write tests for all new features
  • Test on multiple platforms when possible
  • Handle platform-specific behavior appropriately
  • Document privilege requirements

Pull Requests

  • Provide clear description of changes
  • Reference related issues
  • Include test results and coverage
  • Update documentation

See CONTRIBUTING.md for project-wide guidelines.


Future Enhancements

Potential improvements for future versions:

Features

  • Auto-adjustment: Detect optimal FD limit based on application needs
  • Monitoring: Built-in FD usage tracking and alerts
  • Cross-process: Coordinate limits across multiple processes
  • Context support: Context-aware limit changes

Platform Support

  • BSD variants: Explicit support and testing
  • Solaris: Native support
  • Plan 9: If feasible

Developer Experience

  • CLI tool: fdlimit check and fdlimit set commands
  • Metrics export: Prometheus/OpenMetrics format
  • Validation: Pre-flight checks for deployment environments

Suggestions are welcome via GitHub issues.


AI Transparency Notice

In accordance with Article 50.4 of the EU AI Act, AI assistance has been used for testing, documentation, and bug fixing under human supervision.


License

MIT License © Nicolas JUHEL

All source files in this package are licensed under the MIT License. See individual files for the full license header.


Resources

Documentation

Related Packages

  • maxstdio - Windows C runtime limit management (used internally)
  • bufferReadCloser - I/O wrappers with close support
  • ioutils - Parent package with additional I/O utilities

Community


Version: Go 1.18+ on Linux, macOS, Windows
Maintained By: fileDescriptor Package Contributors