Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f824c0c
feat(json): Introduce JSON performance optimization with pooling mech…
code-cfernandes Jul 10, 2025
0299891
feat(json): Adicionar suporte para codificação JSON consistente com f…
code-cfernandes Jul 10, 2025
8a7813b
feat(json): Refatorar JsonBuffer para otimização de gerenciamento de …
code-cfernandes Jul 10, 2025
480ce5a
feat(json): Adicionar benchmark e testes para implementação híbrida d…
code-cfernandes Jul 10, 2025
fc33571
feat(tests): Adicionar testes para estimativa de tamanho no JsonBuffe…
code-cfernandes Jul 10, 2025
1804731
feat(json): Refatorar flags de codificação JSON para consistência em …
code-cfernandes Jul 10, 2025
26e3b38
feat(tests): atualizar namespaces para consistência em todos os testes
code-cfernandes Jul 10, 2025
4598853
feat(tests): adicionar testes para validação de configuração do JsonB…
code-cfernandes Jul 10, 2025
1bb9e44
refactor(tests): melhorar a formatação e a legibilidade dos testes de…
code-cfernandes Jul 10, 2025
ae08da7
feat(tests): adicionar teste para garantir que pool_sizes estão orden…
code-cfernandes Jul 10, 2025
ca005ba
feat(tests): adicionar testes para validar o uso de capacidade ótima …
code-cfernandes Jul 10, 2025
933cd39
feat(tests): adicionar testes para validar os limites de pooling de JSON
code-cfernandes Jul 11, 2025
064af89
refactor(tests): atualizar mensagens de exceção para validação de tip…
code-cfernandes Jul 11, 2025
6a68023
refactor(docs): atualizar rotas na documentação para usar sintaxe de …
code-cfernandes Jul 11, 2025
b456e90
docs: atualizar documentação para refletir a sintaxe de roteamento su…
code-cfernandes Jul 11, 2025
d90a33a
fix: corrigir contagem de pools ativos para considerar apenas pools n…
code-cfernandes Jul 11, 2025
ccab7ce
refactor(tests): simplificar mensagens de exceção para validação de c…
code-cfernandes Jul 11, 2025
58e0e84
fix: atualizar links de documentação para refletir nova URL
code-cfernandes Jul 11, 2025
2e8d02c
refactor: alterar constantes de estimativa de tamanho para público no…
code-cfernandes Jul 11, 2025
3dfd79a
feat: adicionar suporte a constantes públicas para configuração e tes…
code-cfernandes Jul 11, 2025
b270540
refactor(tests): ajustar configuração do JsonBufferPool para usar val…
code-cfernandes Jul 11, 2025
36c6ec9
fix: corrigir parâmetros da função de codificação JSON com pooling pa…
code-cfernandes Jul 11, 2025
eb947ac
feat(tests): adicionar testes para alinhamento de capacidade no JsonB…
code-cfernandes Jul 11, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,4 @@ NOTES.md
scratch/
benchmarks/**/*.json
CLAUDE.md
proposals/
63 changes: 63 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,69 @@ All notable changes to the PivotPHP Framework will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.1.1] - 2025-07-10

### 🚀 **JSON Optimization Edition**

#### Added
- **High-Performance JSON Buffer Pooling System**: Revolutionary JSON processing optimization
- `JsonBuffer`: Optimized buffer class for JSON operations with automatic expansion
- `JsonBufferPool`: Intelligent pooling system with buffer reuse and size categorization
- **Automatic Integration**: `Response::json()` now uses pooling transparently for optimal performance
- **Smart Detection**: Automatically activates pooling for arrays 10+ elements, objects 5+ properties, strings >1KB
- **Graceful Fallback**: Small datasets use traditional `json_encode()` for best performance
- **Public Constants**: All size estimation and threshold constants are now publicly accessible for advanced usage and testing

- **Performance Monitoring & Statistics**:
- Real-time pool statistics with reuse rates and efficiency metrics
- Configurable pool sizes and buffer categories (small: 1KB, medium: 4KB, large: 16KB, xlarge: 64KB)
- Production-ready monitoring with `JsonBufferPool::getStatistics()`
- Performance tracking for optimization and debugging

- **Developer Experience**:
- **Zero Breaking Changes**: All existing code continues working without modification
- **Transparent Optimization**: Automatic activation based on data characteristics
- **Manual Control**: Direct pool access via `JsonBufferPool::encodeWithPool()` when needed
- **Configuration API**: Production tuning via `JsonBufferPool::configure()`
- **Enhanced Error Handling**: Precise validation messages separating type vs range errors
- **Type Safety**: `encodeWithPool()` now always returns string, simplifying error handling

#### Performance Improvements
- **Sustained Throughput**: 101,000+ JSON operations per second in continuous load tests
- **Memory Efficiency**: 100% buffer reuse rate in high-frequency scenarios
- **Reduced GC Pressure**: Significant reduction in garbage collection overhead
- **Scalable Architecture**: Adaptive pool sizing based on usage patterns

#### Technical Details
- **PSR-12 Compliant**: All new code follows project coding standards
- **Comprehensive Testing**: 84 JSON tests with 329+ assertions covering all functionality
- **Backward Compatible**: No changes required to existing applications
- **Production Ready**: Tested with various data sizes and load patterns
- **Centralized Constants**: All thresholds and size constants are unified to avoid duplication
- **Test Maintainability**: Tests now use constants instead of hardcoded values for better maintainability

#### Files Added
- `src/Json/Pool/JsonBuffer.php`: Core buffer implementation
- `src/Json/Pool/JsonBufferPool.php`: Pool management system
- `tests/Json/Pool/JsonBufferTest.php`: Comprehensive buffer tests
- `tests/Json/Pool/JsonBufferPoolTest.php`: Pool functionality tests
- `benchmarks/JsonPoolingBenchmark.php`: Performance validation tools

#### Files Modified
- `src/Http/Response.php`: Integrated automatic pooling in `json()` method
- Enhanced with smart detection and fallback mechanisms

#### Post-Release Improvements (July 2025)
- **Enhanced Configuration Validation**: Separated type checking from range validation for more precise error messages
- **Improved Type Safety**: `encodeWithPool()` method now has tightened return type (always returns string)
- **Public Constants Exposure**: Made all size estimation and threshold constants public for advanced usage and testing
- **Centralized Thresholds**: Unified pooling decision thresholds across Response.php and JsonBufferPool to eliminate duplication
- **Test Maintainability**: Updated all tests to use constants instead of hardcoded values
- **Documentation Updates**:
- Added comprehensive [Constants Reference Guide](docs/technical/json/CONSTANTS_REFERENCE.md)
- Updated performance guide with recent improvements
- Enhanced error handling documentation

## [1.1.0] - 2025-07-09

### 🚀 **High-Performance Edition**
Expand Down
101 changes: 97 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
- **Arquitetura Moderna**: DI Container, Service Providers, Event System, Extension System e PSR-15.
- **Segurança**: Middlewares robustos para CSRF, XSS, Rate Limiting, JWT, API Key e mais.
- **Extensível**: Sistema de plugins, hooks, providers e integração PSR-14.
- **Qualidade**: 315+ testes, PHPStan Level 9, PSR-12, cobertura completa.
- **🆕 v1.0.1**: Suporte a validação avançada de rotas com regex e constraints.
- **🚀 v1.0.1**: Suporte PSR-7 híbrido, lazy loading, object pooling e otimizações de performance.
- **Qualidade**: 335+ testes, PHPStan Level 9, PSR-12, cobertura completa.
- **🆕 v1.1.0**: High-Performance Edition com circuit breaker, load shedding e pooling avançado.
- **🚀 v1.1.1**: JSON Optimization Edition com pooling automático e 101k+ ops/sec sustentados.

---

Expand All @@ -37,7 +37,8 @@
- 📚 **OpenAPI/Swagger**
- 🔄 **PSR-7 Híbrido**
- ♻️ **Object Pooling**
- ⚡ **Performance**
- 🚀 **JSON Optimization** (v1.1.1)
- ⚡ **Performance Extrema**
- 🧪 **Qualidade e Testes**

---
Expand Down Expand Up @@ -109,6 +110,53 @@ $app->get('/posts/:year<\d{4}>/:month<\d{2}>/:slug<slug>', function($req, $res)
$app->run();
```

### 🛣️ Sintaxes de Roteamento Suportadas

O PivotPHP suporta múltiplas sintaxes para definir handlers de rota:

```php
// ✅ Closure/Função Anônima (Recomendado)
$app->get('/users', function($req, $res) {
return $res->json(['users' => []]);
});

// ✅ Array Callable com classe
$app->get('/users', [UserController::class, 'index']);

// ✅ Função nomeada
function getUsersHandler($req, $res) {
return $res->json(['users' => []]);
}
$app->get('/users', 'getUsersHandler');

// ❌ NÃO suportado - String no formato Controller@method
// $app->get('/users', 'UserController@index'); // ERRO!
```

**Exemplo com Controller:**

```php
<?php

class UserController
{
public function index($req, $res)
{
return $res->json(['users' => User::all()]);
}

public function show($req, $res)
{
$id = $req->param('id');
return $res->json(['user' => User::find($id)]);
}
}

// Registrar rotas com array callable
$app->get('/users', [UserController::class, 'index']);
$app->get('/users/:id', [UserController::class, 'show']);
```

### 🔄 Suporte PSR-7 Híbrido

O PivotPHP oferece **compatibilidade híbrida** com PSR-7, mantendo a facilidade da API Express.js enquanto implementa completamente as interfaces PSR-7:
Expand Down Expand Up @@ -151,6 +199,51 @@ $response = OptimizedHttpFactory::createResponse();
- ✅ **API Express.js** mantida para produtividade
- ✅ **Zero breaking changes** - código existente funciona sem alterações

### 🚀 JSON Optimization (v1.1.1)

O PivotPHP v1.1.1 introduz um sistema revolucionário de otimização JSON que melhora drasticamente a performance através de buffer pooling inteligente:

```php
// Otimização automática - zero configuração necessária
$app->get('/api/users', function($req, $res) {
$users = User::all(); // 1000+ usuários

// Automaticamente usa pooling para datasets grandes
return $res->json($users); // 101k+ ops/sec sustentados
});

// Controle manual para casos específicos
use PivotPHP\Core\Json\Pool\JsonBufferPool;

// Encoding direto com pooling
$json = JsonBufferPool::encodeWithPool($largeData);

// Configuração para alta carga de produção
JsonBufferPool::configure([
'max_pool_size' => 500,
'default_capacity' => 16384, // 16KB buffers
'size_categories' => [
'small' => 4096, // 4KB
'medium' => 16384, // 16KB
'large' => 65536, // 64KB
'xlarge' => 262144 // 256KB
]
]);

// Monitoramento em tempo real
$stats = JsonBufferPool::getStatistics();
echo "Reuse rate: {$stats['reuse_rate']}%"; // Target: 80%+
echo "Operations: {$stats['total_operations']}";
```

**Características da Otimização JSON:**
- ✅ **Detecção automática** - ativa pooling para arrays 10+ elementos, objetos 5+ propriedades
- ✅ **Fallback inteligente** - dados pequenos usam `json_encode()` tradicional
- ✅ **101k+ ops/sec** sustentados em testes de carga contínua
- ✅ **100% reuso** de buffers em cenários de alta frequência
- ✅ **Zero configuração** - funciona automaticamente com código existente
- ✅ **Monitoramento integrado** - estatísticas detalhadas para otimização

### 📖 Documentação OpenAPI/Swagger

O PivotPHP inclui suporte integrado para geração automática de documentação OpenAPI:
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.1.0
1.1.1
114 changes: 114 additions & 0 deletions benchmarks/JsonBufferRefactorBenchmark.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use PivotPHP\Core\Json\Pool\JsonBuffer;
use PivotPHP\Core\Json\Pool\JsonBufferPool;

/**
* Benchmark to test JsonBuffer refactoring performance
*/
class JsonBufferRefactorBenchmark
{
public function run(): void
{
echo "🧪 JsonBuffer Refactoring Performance Test\n";
echo "==========================================\n\n";

$iterations = 10000;
$testData = [
'message' => 'Hello, World!',
'timestamp' => time(),
'unicode' => '🚀 Performance Test',
'url' => 'https://example.com/test',
'nested' => [
'level1' => ['level2' => ['level3' => 'deep value']],
'array' => range(1, 50)
]
];

// Test 1: Direct JsonBuffer usage
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$buffer = new JsonBuffer();
$buffer->appendJson($testData);
$result = $buffer->finalize();
}
$directTime = microtime(true) - $start;

// Test 2: JsonBufferPool usage
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$result = JsonBufferPool::encodeWithPool($testData);
}
$poolTime = microtime(true) - $start;

// Test 3: Traditional json_encode
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$result = json_encode($testData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
$traditionalTime = microtime(true) - $start;

// Calculate performance metrics
$directOps = $iterations / $directTime;
$poolOps = $iterations / $poolTime;
$traditionalOps = $iterations / $traditionalTime;

echo "📊 Results ({$iterations} iterations):\n";
echo "Direct JsonBuffer: " . number_format($directOps, 0) . " ops/sec\n";
echo "JsonBufferPool: " . number_format($poolOps, 0) . " ops/sec\n";
echo "Traditional encode: " . number_format($traditionalOps, 0) . " ops/sec\n\n";

echo "⚡ Performance ratios:\n";
echo "Buffer vs Traditional: " . number_format($directOps / $traditionalOps, 2) . "x\n";
echo "Pool vs Traditional: " . number_format($poolOps / $traditionalOps, 2) . "x\n";
echo "Pool vs Direct: " . number_format($poolOps / $directOps, 2) . "x\n\n";

// Test memory efficiency
$memStart = memory_get_usage();

// Create and reuse buffers
$buffer = new JsonBuffer();
for ($i = 0; $i < 1000; $i++) {
$buffer->appendJson($testData);
$buffer->finalize();
$buffer->reset();
}

$memAfterReuse = memory_get_usage();
$reuseMemory = $memAfterReuse - $memStart;

// Create new buffers each time
$memStart = memory_get_usage();
for ($i = 0; $i < 1000; $i++) {
$buffer = new JsonBuffer();
$buffer->appendJson($testData);
$buffer->finalize();
}
$memAfterNew = memory_get_usage();
$newMemory = $memAfterNew - $memStart;

echo "💾 Memory efficiency (1000 operations):\n";
echo "Buffer reuse: " . number_format($reuseMemory / 1024, 2) . " KB\n";
echo "New buffers: " . number_format($newMemory / 1024, 2) . " KB\n";
echo "Memory saved: " . number_format(($newMemory - $reuseMemory) / 1024, 2) . " KB\n";
echo "Efficiency: " . number_format((1 - $reuseMemory / $newMemory) * 100, 1) . "% less memory\n\n";

// Pool statistics
echo "🏊 Pool Statistics:\n";
$stats = JsonBufferPool::getStatistics();
echo "Reuse rate: " . $stats['reuse_rate'] . "%\n";
echo "Total ops: " . $stats['total_operations'] . "\n";
echo "Current usage: " . $stats['current_usage'] . "\n";
echo "Peak usage: " . $stats['peak_usage'] . "\n\n";

echo "✅ Refactoring Performance Test Complete!\n";
}
}

// Run the benchmark
$benchmark = new JsonBufferRefactorBenchmark();
$benchmark->run();
Loading