Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
133 changes: 110 additions & 23 deletions docs/en/api-reference.md
Original file line number Diff line number Diff line change
@@ -1,50 +1,137 @@
# API Reference

## Config
## Command Line Interface

### ncorn

```bash
ncorn module:app [OPTIONS]
```

Main entry point for running ncorn server.

### ncorn config

```bash
ncorn config
```

Creates default `ncorn.json` configuration file.

## Python API

### Config

```python
from ncorn.config import Config
```

Configuration class for ncorn server.

```python
config = Config(
host="127.0.0.1",
port=8000,
workers=1,
reload=False,
max_body_size=16777216,
header_timeout=30.0,
body_timeout=60.0,
keepalive_timeout=5.0,
max_headers=100,
max_keepalive_requests=100,
rate_limit_requests=100,
rate_limit_window=60.0,
max_body_size=16 * 1024 * 1024,
ssl_keyfile=None,
ssl_certfile=None,
ssl_version=5,
)
```

## HTTPServer
#### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `host` | str | "127.0.0.1" | IP address to bind |
| `port` | int | 8000 | Port number |
| `workers` | int | 1 | Number of worker processes |
| `reload` | bool | False | Enable auto-reload |
| `max_body_size` | int | 16777216 | Max request body size |
| `max_header_size` | int | 8192 | Max single header size |
| `max_headers_total_size` | int | 65536 | Max total headers size |
| `header_timeout` | float | 30.0 | Header read timeout |
| `body_timeout` | float | 60.0 | Body read timeout |
| `request_timeout` | float | 10.0 | Request processing timeout |
| `keepalive_timeout` | float | 5.0 | Keep-alive timeout |
| `keepalive_requests` | int | 100 | Max requests per connection |
| `max_headers` | int | 100 | Max number of headers |
| `max_connections` | int | 1000 | Max concurrent connections |
| `max_connections_per_ip` | int | 50 | Max connections per IP |
| `rate_limit_requests` | int | 100 | Requests per window |
| `rate_limit_window` | float | 60.0 | Rate limit window |
| `ssl_keyfile` | str | None | SSL key file path |
| `ssl_certfile` | str | None | SSL certificate path |
| `ssl_version` | int | 5 | TLS version (2-5) |

### HTTPServer

```python
from ncorn.server import HTTPServer
from ncorn.config import Config
from myapp import app
```

config = Config(host="0.0.0.0", port=8080)
server = HTTPServer(app, config)
HTTP server class.

# Start server
```python
server = HTTPServer(app, config)
await server.start()

# Stop server
await server.stop()
```

## Logger
#### Methods

##### start(show_banner=True)

Start the HTTP server.

##### stop()

Gracefully stop the server.

### CLI Functions

```python
from ncorn.logging import logger
from ncorn.cli import import_app, parse_args, main
```

#### import_app(app_spec: str)

Import FastAPI app from "module:app" string.

#### parse_args(args: Optional[list[str]] = None) -> argparse.Namespace

Parse command line arguments.

#### main(args: Optional[list[str]] = None) -> None

Main entry point.

### Middleware

logger.info("Message")
logger.warning("Message")
logger.error("Message")
logger.success("Message")
```python
from ncorn.middleware import (
ValidationMiddleware,
RateLimitMiddleware,
MiddlewareChain,
)
```

#### ValidationMiddleware

Validates HTTP requests (headers, body size).

#### RateLimitMiddleware

Implements IP-based rate limiting.

#### MiddlewareChain

Chains multiple middleware together.

## Exceptions

### ncorn exceptions

ncorn uses standard Python exceptions. Check individual middleware documentation for specific error handling.
48 changes: 0 additions & 48 deletions docs/en/cli.md

This file was deleted.

70 changes: 70 additions & 0 deletions docs/en/concepts/asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# ASGI

ASGI (Asynchronous Server Gateway Interface) is a standard interface between Python web servers and applications.

## Overview

ASGI is a specification that describes how async web applications should communicate with web servers. It was designed to replace WSGI (PEP 333) for async frameworks.

## Key Concepts

### Scope

The `scope` is a dictionary containing information about the connection:

```python
{
"type": "http",
"method": "GET",
"path": "/",
"query_string": b"",
"headers": [(b"host", b"localhost")],
"client": ("127.0.0.1", 8000),
"server": ("127.0.0.1", 8000),
"scheme": "http",
}
```

### Receive

The `receive` callable waits for incoming data:

```python
message = await receive()
# Returns: {"type": "http.request", "body": b"...", "more_body": bool}
```

### Send

The `send` callable sends response data:

```python
# Start response
await send({
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"application/json")],
})

# Send body
await send({
"type": "http.response.body",
"body": b'{"message": "hello"}',
})
```

## HTTP Types

- `http` - Regular HTTP/1.1 connections
- `websocket` - WebSocket connections
- `lifespan` - Application lifecycle events

## ncorn ASGI Implementation

ncorn implements a full ASGI server:

- Parses HTTP/1.1 requests
- Builds ASGI scope dictionary
- Handles request/response lifecycle
- Supports keep-alive connections
- Implements HTTP/1.1 only (WebSocket coming soon)
93 changes: 93 additions & 0 deletions docs/en/concepts/lifespan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Lifespan

The lifespan protocol allows applications to perform startup and shutdown tasks.

## Overview

The lifespan protocol is part of ASGI and enables applications to:

- Initialize resources on startup
- Clean up resources on shutdown

## Usage with FastAPI

FastAPI handles lifespan automatically, but you can define custom handlers:

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
print("Starting up...")
await connect_to_database()

yield

# Shutdown
print("Shutting down...")
await close_database()

app = FastAPI(lifespan=lifespan)
```

## Manual ASGI Implementation

If you're implementing ASGI directly:

```python
async def app(scope, receive, send):
if scope["type"] == "lifespan":
while True:
message = await receive()

if message["type"] == "lifespan.startup":
# Initialize resources
await send({"type": "lifespan.startup.complete"})

elif message["type"] == "lifespan.shutdown":
# Clean up resources
await send({"type": "lifespan.shutdown.complete"})
break
```

## ncorn Lifespan

ncorn fully supports the lifespan protocol:

- Calls startup events when server starts
- Calls shutdown events when server stops
- Handles graceful shutdown properly

## Startup Event

Triggered when the server is ready to accept connections:

```python
{"type": "lifespan.startup"}
```

Your app should respond with:

```python
{"type": "lifespan.startup.complete"}
# or
{"type": "lifespan.startup.failed", "message": "error reason"}
```

## Shutdown Event

Triggered when the server is shutting down:

```python
{"type": "lifespan.shutdown"}
```

Your app should respond with:

```python
{"type": "lifespan.shutdown.complete"}
# or
{"type": "lifespan.shutdown.failed", "message": "error reason"}
```
Loading
Loading