Metadata-Version: 2.4
Name: bfast-py
Version: 1.12.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: pydantic>=2.0
Requires-Dist: numpy
Requires-Dist: lz4>=4.3.3
Requires-Dist: fastapi ; extra == 'all'
Requires-Dist: django>=4.2 ; extra == 'all'
Requires-Dist: django-ninja>=1.0 ; extra == 'all'
Requires-Dist: polars>=0.20.0 ; extra == 'all'
Requires-Dist: pandas>=2.0.0 ; extra == 'all'
Requires-Dist: mcp>=1.0.0 ; extra == 'all'
Requires-Dist: fastmcp>=2.0.0 ; extra == 'all'
Requires-Dist: polars>=0.20.0 ; extra == 'data'
Requires-Dist: pandas>=2.0.0 ; extra == 'data'
Requires-Dist: django>=4.2 ; extra == 'dev'
Requires-Dist: django-ninja>=1.0 ; extra == 'dev'
Requires-Dist: polars>=0.20.0 ; extra == 'dev'
Requires-Dist: pandas>=2.0.0 ; extra == 'dev'
Requires-Dist: matplotlib>=3.7.5 ; extra == 'dev'
Requires-Dist: orjson>=3.10.15 ; extra == 'dev'
Requires-Dist: mkdocs-material>=9.7.1 ; extra == 'dev'
Requires-Dist: mkdocstrings[python]>=0.26.1 ; extra == 'dev'
Requires-Dist: pytest>=7.0 ; extra == 'dev'
Requires-Dist: black>=23.0 ; extra == 'dev'
Requires-Dist: ruff>=0.1.0 ; extra == 'dev'
Requires-Dist: django>=4.2 ; extra == 'django'
Requires-Dist: django-ninja>=1.0 ; extra == 'django'
Requires-Dist: fastapi ; extra == 'fastapi'
Requires-Dist: mcp>=1.0.0 ; extra == 'fastmcp'
Requires-Dist: fastmcp>=2.0.0 ; extra == 'fastmcp'
Requires-Dist: mcp>=1.0.0 ; extra == 'mcp'
Provides-Extra: all
Provides-Extra: data
Provides-Extra: dev
Provides-Extra: django
Provides-Extra: fastapi
Provides-Extra: fastmcp
Provides-Extra: mcp
License-File: LICENSE
Summary: ⚡ B-FAST (Binary Fast Adaptive Serialization Transfer) - Protocolo de serialização binária de ultra-alta performance, desenvolvido em Rust para o ecossistema Python e TypeScript
Keywords: serialization,binary,fast,rust,pydantic,numpy
Author: marcelomarkus
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://marcelomarkus.github.io/b-fast/
Project-URL: Homepage, https://github.com/marcelomarkus/b-fast
Project-URL: Issues, https://github.com/marcelomarkus/b-fast/issues
Project-URL: Repository, https://github.com/marcelomarkus/b-fast

<p align="center">
  <img src="docs/assets/bfast-black.svg#gh-light-mode-only" alt="B-FAST" width="500" />
  <img src="docs/assets/bfast-white.svg#gh-dark-mode-only" alt="B-FAST" width="500" />
</p>

<p align="center">
  <a href="https://github.com/marcelomarkus/b-fast/actions/workflows/tests.yml"><img src="https://github.com/marcelomarkus/b-fast/actions/workflows/tests.yml/badge.svg" alt="CI"></a>
  <a href="https://marcelomarkus.github.io/b-fast/"><img src="https://github.com/marcelomarkus/b-fast/actions/workflows/docs.yml/badge.svg" alt="Documentation"></a>
  <a href="https://pypi.org/project/bfast-py/"><img src="https://img.shields.io/pypi/v/bfast-py?color=blue&logo=pypi&logoColor=white" alt="PyPI version"></a>
  <a href="https://pypi.org/project/bfast-py/"><img src="https://img.shields.io/pypi/pyversions/bfast-py?logo=python&logoColor=white" alt="Python versions"></a>
  <a href="https://www.npmjs.com/package/bfast-client"><img src="https://img.shields.io/npm/v/bfast-client?color=crimson&logo=npm&logoColor=white" alt="npm version"></a>
  <a href="https://chromewebstore.google.com/detail/b-fast-inspector/nbjopcagmflkmgfppkeijcpbkobkgehp"><img src="https://img.shields.io/badge/Chrome%20Web%20Store-B--FAST%20Inspector-blue?logo=googlechrome&logoColor=white" alt="Chrome Web Store"></a>
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
  <a href="https://marcelomarkus.github.io/b-fast/performance/"><img src="https://img.shields.io/badge/Speedup-Up%20to%205.7x%20vs%20orjson-brightgreen?logo=speedtest&logoColor=white" alt="Performance"></a>
  <a href="https://app.codspeed.io/marcelomarkus/b-fast?utm_source=badge"><img src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" alt="CodSpeed"/></a>
</p>

<h3 align="center">The high-speed binary wire for modern Python & TypeScript.</h3>
<p align="center">
  <strong>Faster than orjson. Simpler than Protobuf. Inspectable in your browser.</strong>
</p>

B-FAST is a next-generation binary serialization protocol designed to replace JSON and legacy binary formats on critical routes. It delivers sub-microsecond latency, native Pydantic integration, and streaming performance with zero schema boilerplate.

> *"Performance is not just about speed — it's about efficiency where it matters most."*

### ⚡ At a Glance: The Modern Binary Paradigm

| Capability | JSON / orjson | Protocol Buffers (gRPC) | ⚡ **B-FAST** |
|:---|:---:|:---:|:---:|
| **Wire Format** | Text (Heavy) | Binary Compact | **Binary + Adaptive Compression** |
| **Schema Overhead** | ❌ None | ⚠️ Strict `.proto` compilation | **❌ None (Plug & Play)** |
| **Pydantic & Python Models** | Slow (`model_dump()`) | Manual field mapping | **⚡ Native Memory Access** |
| **Browser DevTools** | ✅ Native readable text | ❌ Raw unreadable binary | **⚡ [B-FAST Inspector](https://chromewebstore.google.com/detail/b-fast-inspector/nbjopcagmflkmgfppkeijcpbkobkgehp) Extension** |
| **Streaming Throughput** | ~22,000 frames/s | Moderate | **🚀 > 3,100,000 frames/s** |
| **Scientific & NumPy Data** | Slow array serialization | Manual raw bytes | **⚡ Native Array Speed (14-96x)** |

## 🚀 Why B-FAST?
- **Sub-Microsecond Latency:** Encodes 100 structured objects in 676 ns and decodes in 754 ns.
- **Pydantic Native:** Reads Pydantic model attributes directly from memory, skipping slow `.model_dump()` serialization.
- **NumPy Native:** Serializes tensors and numeric arrays directly, achieving 14-96x speedup vs JSON/orjson.
- **Parallel Compression:** Multi-thread processing for large payloads (>1MB).
- **Zero-Friction DevTools:** Full browser inspection via the official B-FAST Inspector extension.

## 💡 The Philosophy: Smart Serialization

B-FAST was born from the recognition that modern applications need more than just fast serialization — they need **smart serialization** that adapts to real-world constraints. After extensive optimization, B-FAST operates in the **sub-microsecond realm** (**676 ns** encode / **754 ns** decode for 100 objects), achieving **4.1x faster** than orjson for objects, **5.7x faster** on slow networks, and over **3,180,000 frames/s** in streaming protocol.

> **Philosophy:** We believe that the future of data transfer lies not in raw CPU speed alone, but in intelligent protocols that minimize network overhead while maintaining excellent performance. B-FAST represents our contribution to a more efficient, bandwidth-conscious web.

## 📊 Benchmarks (State-of-the-Art Results)

<p align="center">
  <img src="benchmark_chart.png" alt="B-FAST Performance Benchmarks" width="900">
</p>

<p align="center">
  <em>Comprehensive empirical benchmarks: B-FAST delivers 1.9x faster encode and 4.6x faster decode than Protobuf in real-world Python, 4.1x faster encoding than orjson, and over 3.18M frames/sec sustained streaming throughput.</em>
</p>

### ⚡ Sub-Microsecond Realm (100 Structured Objects)
| Operation | Time (ns) | Equivalent Ops / Second | Speedup vs Baseline |
|-----------|-----------|-------------------------|---------------------|
| **Encode (100 objects)** | **676 ns** | **> 1,470,000 ops/s** | **🚀 2.1x faster** |
| **Decode (100 objects)** | **754 ns** | **> 1,320,000 ops/s** | **🚀 2.6x faster** |

### 🚀 Simple Objects (10,000)
| Format | Time (ms) | Speedup vs JSON | Speedup vs orjson |
|--------|:---------:|:---------------:|:-----------------:|
| JSON (stdlib) | 12.0ms | 1.0x *(Base)* | — |
| orjson | 8.19ms | 1.5x | 1.0x *(Base)* |
| **B-FAST** | **2.01ms** | **🚀 6.0x faster** | **⚡ 4.1x faster** |

*B-FAST is **4.1x faster** than Python's fastest JSON library (`orjson`) and **6.0x faster** than standard `json`.*

### 🌊 Streaming Protocol (1,000 frames)
| Metric | Performance | Speedup / Throughput |
|--------|-------------|----------------------|
| **Streaming Decode (Aligned)** | **0.31ms (314µs)** | **~3,180,000 frames/s** (145x vs NDJSON) |
| **Streaming Decode (Fragmented)** | **0.32ms (322µs)** | **~3,100,000 frames/s** (Zero TCP penalty) |
| **Single Frame Latency** | **2.0ns** | **Real-time instant parsing** |
| **Sustained Stream Throughput** | **> 3,100,000 frames/s** | **Ultra-high-frequency telemetry & AI feeds** |

### 🔄 Round-Trip (Encode + Network + Decode)
Complete test including network transfer and deserialization (10,000 objects):

#### 📡 100 Mbps (Slow Network)
| Format | Total Time | Speedup vs orjson |
|--------|------------|-------------------|
| JSON | 114.5ms | 0.8x |
| orjson | 91.7ms | 1.0x |
| **B-FAST (Compressed)** | **16.1ms** | **🚀 5.7x** |

#### 📡 1 Gbps (Fast Network)
| Format | Total Time | Speedup vs orjson |
|--------|------------|-------------------|
| JSON | 29.4ms | 0.5x |
| orjson | 15.3ms | 1.0x |
| **B-FAST (Compressed)** | **7.2ms** | **🚀 2.1x** |

#### 📡 10 Gbps (Ultra-Fast Network)
| Format | Total Time | Speedup vs orjson |
|--------|------------|-------------------|
| JSON | 20.9ms | 0.4x |
| orjson | 7.7ms | 1.0x |
| **B-FAST (Compressed)** | **6.3ms** | **🚀 1.2x** |

### 🥊 B-FAST vs Protocol Buffers (Protobuf)

Protocol Buffers is widely recognized as an industry standard for binary serialization. However, in modern Python applications (such as FastAPI services, APIs, and data microservices), working with Protobuf introduces significant friction and translation overhead.

In an end-to-end benchmark serializing and deserializing 10,000 structured application objects:

| Feature / Metric | Protocol Buffers | B-FAST | Advantage |
|------------------|:----------------:|:------:|-----------|
| **Schema Overhead** | Requires `.proto` files & compilation | **None** (Plug-and-play) | No boilerplate or build step |
| **Real-World Encode** *(From application models)* | 13.5ms *(Model → Proto → Wire)* | **7.2ms** *(Direct)* | **🚀 1.87x faster** |
| **Full Decode** *(To native Python dicts/lists)* | 87.1ms *(`MessageToDict`)* | **18.9ms** *(Native)* | **🚀 4.6x faster** |
| **Compressed Payload** | 374 KB | **410 KB** | Comparable compactness |
| **DevTools Debugging** | Requires external proxies & schemas | **Official DevTools Extension** | Inspect in browser Network tab |

**Why this matters in practice:**
- **No Translation Tax:** While Protobuf is fast in pure C++, Python applications spend substantial CPU cycles copying data between application models (like Pydantic or dicts) and generated Protobuf message classes. B-FAST works directly with your existing Python objects.
- **Immediate Usability:** Protobuf's initial decode only provides access to specialized message wrappers; converting them into standard Python collections takes over 87ms. B-FAST yields full, native Python structures immediately upon decoding.
- **Ergonomics:** You get compact binary serialization and high throughput without defining `.proto` contracts, maintaining schema versions, or running compiler toolchains.

### 🎯 Ideal Use Cases
- **⚡ Microservices & High-Frequency Trading**: Sub-microsecond latency (< 800 ns per 100 objects)
- **🌊 Real-time Streaming & AI Telemetry**: > 3,100,000 frames/s with zero TCP fragmentation penalty
- **📱 Mobile/IoT**: 89% data savings + 5.7x performance on slow networks
- **🌐 APIs with slow networks**: Up to 5.7x faster than orjson
- **📊 Data pipelines**: 14-96x speedup for NumPy arrays
- **🗜️ Storage/Cache**: Superior integrated compression
- **🚀 Simple objects**: 4.1x faster than orjson

## 📦 Installation

### Backend (Python)
```bash
# Basic installation
pip install bfast-py

# With FastAPI support
pip install "bfast-py[fastapi]"
```
or with `uv`:
```bash
uv add bfast-py
# or
uv add "bfast-py[fastapi]"
```

### Frontend (TypeScript)
```bash
npm install bfast-client
```

## 🛠️ How to Use

### Backend (Python)

#### 0. Simple Serialization (1-Liner)
```python
import b_fast

# Automatic compression enabled by default
binary = b_fast.encode({"items": [1, 2, 3], "status": "ok"})
data = b_fast.decode(binary)

# Or via BFast instance
bf = b_fast.BFast()
binary = bf.encode_packed(data)
```

#### 1. FastAPI Integrations ⭐

B-FAST supports two integration styles for FastAPI:

##### Option A: Transparent Content Negotiation (`BFastMiddleware`)
Zero-code route refactoring. Existing routes return JSON by default, but automatically return compressed B-FAST binary when requested by clients via `Accept: application/x-bfast`:

```python
from fastapi import FastAPI
from b_fast.fastapi import BFastMiddleware

app = FastAPI()
app.add_middleware(BFastMiddleware, compress=True)


@app.get("/users")
def get_users():
    # Returns standard JSON to browsers
    # Automatically returns B-FAST binary when requested via Accept: application/x-bfast!
    return [{"id": i, "name": f"User {i}"} for i in range(1000)]
```

##### Option B: Direct Route Integration (`BFastResponse` & `BFastStreamingResponse`)
Explicit route control without middleware:

```python
from fastapi import FastAPI
from pydantic import BaseModel
from b_fast import BFastResponse, BFastStreamingResponse

app = FastAPI()


class User(BaseModel):
    id: int
    name: str


# 1. Explicit B-FAST binary response
@app.get("/users", response_class=BFastResponse)
async def get_users():
    # Returns binary B-FAST data with automatic adaptive compression
    return [User(id=i, name=f"User {i}") for i in range(1000)]


# 2. ⚡ Streamable HTTP (Progressive Chunks, 3.18M frames/sec)
@app.get("/users/stream")
async def stream_users():
    async def user_generator():
        for i in range(1000):
            yield User(id=i, name=f"User {i}")

    # Streams framed chunks with Content-Type: application/x-bfast-stream
    return BFastStreamingResponse(user_generator())
```

#### 2. Django Ninja & Django
```python
from ninja import NinjaAPI
from b_fast.django import BFastRenderer, BFastHttpResponse

# Django Ninja with BFastRenderer
api = NinjaAPI(renderer=BFastRenderer())

@api.get("/users")
def get_users(request):
    return [{"id": i, "name": f"User {i}"} for i in range(1000)]

# Standard Django View
def django_view(request):
    return BFastHttpResponse({"status": "ok"})
```

#### 3. Polars & Pandas DataFrames
```python
from b_fast import BFast, encode_dataframe
import polars as pl

df = pl.DataFrame({"id": [1, 2, 3], "score": [95.0, 88.0, 92.5]})

# Direct native serialization in BFast
packed = BFast().encode_packed(df, compress=True)

# Or with orientation control ('records', 'columns', 'split')
col_data = encode_dataframe(df, orient="columns")
```

#### 4. FastMCP 2.0 (AI Agent Tools)
```python
from b_fast import FastMCPBFast, bfast_tool

mcp = FastMCPBFast("data-service")


@mcp.tool()
@bfast_tool()
def query_records(limit: int = 100):
    return [{"id": i, "metric": i * 1.5} for i in range(limit)]
```

#### 5. Socket Streaming & Native Transport
Stream framed B-FAST data directly into TCP/UNIX sockets with native OS acceleration on Linux:

```python
import socket
from b_fast import BFastSocketStreamer

# Direct socket streaming with native transport (sync or async)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect(("127.0.0.1", 9000))
    with BFastSocketStreamer(sock, compress=True, native=True) as streamer:
        streamer.stream([{"id": i, "val": i * 1.5} for i in range(1000)])
```

### Frontend (TypeScript)

#### 0. Zero-Code Transparent Acceleration (Drop-in) ⭐
```typescript
import 'bfast-client/auto';

// Existing fetch calls automatically negotiate B-FAST and decode transparently!
const response = await fetch('/users');
const users = await response.json(); // Transparently!
```

#### 1. Fetch & TanStack Query (React Query)
```typescript
import { bfastFetch, bfastQueryOptions } from 'bfast-client';
import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';

const UserSchema = z.object({ id: z.number(), name: z.string() });
type User = z.infer<typeof UserSchema>;

// Direct Fetch
const users = await bfastFetch<User[]>('/users');

// In React with TanStack Query
function UserComponent() {
    const { data: user } = useQuery(
        bfastQueryOptions<User>({
            queryKey: ['user', 1],
            url: '/users/1',
            schema: UserSchema, // Runtime schema validation
        })
    );
    return <div>{user?.name}</div>;
}
```

#### 2. Streamable HTTP (Progressive Stream)
```typescript
import { decodeReadableStream } from 'bfast-client';

async function streamData() {
    const response = await fetch('/users/stream');
    
    // Iterates over incoming network frames in real-time
    for await (const user of decodeReadableStream(response.body!)) {
        console.log('Received user in real-time:', user);
    }
}
```

#### 3. Columnar Table (`BFastTable`)
```typescript
import { BFastTable } from 'bfast-client';

const table = BFastTable.from(buffer);
const prices = table.getFloat64Array('price');
const totalPrice = table.aggregate('price', 'sum');
table.free();
```

### 🔍 DevTools Extension: B-FAST Inspector

Binary protocols no longer mean losing visibility in your browser. With the official **B-FAST Inspector** extension, you get the same inspection experience you enjoy with JSON:

- ⚡ **Auto-Detection:** Automatically intercepts and decodes `application/x-bfast` network traffic in DevTools.
- 🌳 **Interactive Tree View:** Explore parsed responses as collapsible, color-coded interactive trees.
- ⏱️ **Metrics & Savings:** Live breakdown of bandwidth reduction and decode latencies.
- 📸 **Social Proof Cards:** Generates sharable benchmark cards highlighting your speedups.

👉 **Install directly from the [Chrome Web Store](https://chromewebstore.google.com/detail/b-fast-inspector/nbjopcagmflkmgfppkeijcpbkobkgehp)**

## 🤖 AI Assistants & Coding Agents (`llms.txt`)

B-FAST provides a standardized, curated **[`llms.txt`](https://marcelomarkus.github.io/b-fast/llms.txt)** endpoint for AI tools (**OpenCode**, **Cursor**, **Claude Code**, **ChatGPT**, **Windsurf**, and **GitHub Copilot**).

Prompt your AI assistant directly:
```markdown
Follow the B-FAST guidelines at https://marcelomarkus.github.io/b-fast/llms.txt to implement binary endpoints.
```

## 📄 License
Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
