apigate 0.2.5

Macro-driven API gateway for Rust — declarative routing, request transformation, and reverse proxying built on axum
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# ApiGate

Типизированный API-шлюз (reverse proxy) для микросервисов на Rust.

Макросы генерируют маршруты с валидацией `Path / Query / Json / Form / Multipart`, хуками `before`, преобразованием `map` и runtime-политиками (балансировка, routing, таймауты). Внутри — `axum`, снаружи — только API `apigate`.

---

## Быстрый старт

```rust
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cfg = AppConfig::from_env();

    let app = apigate::App::builder()
        .mount_service(sales::routes(), cfg.sales_backends)
        .mount_service(files::routes(), cfg.files_backends)
        .state(cfg.db_pool.clone())
        .state(cfg.auth_config.clone())
        .request_timeout(std::time::Duration::from_secs(10))
        .connect_timeout(std::time::Duration::from_secs(3))
        .pool_idle_timeout(std::time::Duration::from_secs(60))
        .policy("sales_default", apigate::Policy::header_sticky("x-user-id"))
        // optional: emit built-in runtime events through tracing
        // .enable_default_tracing()
        // optional: set custom runtime observer for logs/metrics/audit
        // .runtime_observer(my_runtime_observer)
        // optional: add external tower/axum layers
        // .with_router(|r| r.layer(tower_http::trace::TraceLayer::new_for_http()))
        .build()?;

    apigate::run(cfg.listen, app).await
}
```

---

## Сервис

```rust
#[apigate::service(prefix = "/sales", policy = "sales_default")]
mod sales {
    use super::*;

    #[apigate::get("/ping")]
    async fn ping() {}

    #[apigate::get("/{id}", path = SaleIdPath, before = [auth])]
    async fn get_by_id() {}

    #[apigate::get("/public", to = "/internal")]
    async fn public_alias() {}

    #[apigate::post("/buy", json = BuyInput, before = [auth], map = remap_buy)]
    async fn buy() {}

    #[apigate::post("/upload", multipart, before = [auth])]
    async fn upload() {}
}
```

| Параметр `service` | Описание |
|---|---|
| `name` | Имя сервиса = ключ `.backend(...)`. По умолчанию — имя модуля |
| `prefix` | Внешний URL-префикс. По умолчанию — `""` (корень) |
| `policy` | Политика по умолчанию для всех маршрутов сервиса |

---

## Атрибуты маршрута

```rust
#[apigate::get("/path", to = "/rewrite", path = T, query = T, json = T, form = T,
               multipart, before = [hook1, hook2], map = map_fn, policy = "name")]
```

| Атрибут | Описание |
|---|---|
| `"/path"` | Внешний путь. Поддерживает `/{param}` |
| `to` | Путь в upstream. Без `to` — проксирует как есть (`StripPrefix`). Поддерживает `/{param}` |
| `path = T` | Десериализует и валидирует path-параметры (`T: Deserialize + Clone`). 400 при ошибке |
| `query = T` | Валидирует query string |
| `json = T` | Валидирует JSON body |
| `form = T` | Валидирует `application/x-www-form-urlencoded` body |
| `multipart` | Passthrough для `multipart/form-data` |
| `before = [...]` | Хуки, выполняемые до проксирования |
| `map = fn` | Преобразование `query/json/form` перед отправкой в upstream |
| `policy = "name"` | Переопределяет политику сервиса для этого маршрута |

> `json`, `form`, `multipart` — взаимоисключающие (один body-режим на маршрут).

---

## Входные данные

### Path

```rust
#[derive(Clone, serde::Deserialize)]
struct SaleIdPath { sale_id: uuid::Uuid }

#[apigate::get("/{sale_id}", path = SaleIdPath)]
async fn get_sale() {}
```

Извлекается **до** хуков, попадает в `RequestScope`. Доступен в хуках как `path: SaleIdPath` (owned) или `path: &SaleIdPath`.

### Query / Json / Form

```rust
#[apigate::get("/search", query = SearchQuery)]           // валидация query
#[apigate::post("/buy", json = BuyInput)]                  // валидация JSON
#[apigate::post("/legacy", form = LegacyForm)]             // валидация form
```

Без `map` — валидация + passthrough оригинального тела. С `map` — преобразование перед отправкой.

### Multipart

```rust
#[apigate::post("/upload", multipart)]
async fn upload() {}
```

Passthrough без чтения тела. `map` не поддерживается.

---

## Хуки (`before`)

Выполняются до проксирования. Работают с заголовками, URI, extensions.

```rust
#[apigate::hook]
async fn auth(ctx: &mut apigate::PartsCtx) -> apigate::HookResult {
    let token = ctx.header("authorization")
        .ok_or_else(|| apigate::ApigateError::unauthorized("missing token"))?;
    ctx.set_header("x-user-id", "...")?;
    Ok(())
}

#[apigate::get("/protected", before = [auth])]
async fn protected() {}
```

---

## Преобразование (`map`)

Типизированное преобразование `query/json/form` перед отправкой в upstream.

```rust
#[apigate::map]
async fn remap_buy(input: PublicBuy) -> apigate::MapResult<ServiceBuy> {
    Ok(ServiceBuy {
        ids: input.sale_ids,
        source: "apigate",
    })
}

#[apigate::post("/buy", json = PublicBuy, before = [auth], map = remap_buy)]
async fn buy() {}
```

Работает аналогично для `query = T, map = ...` и `form = T, map = ...`:
- **query**: map переписывает query string в URI
- **json**: map сериализует результат в новое тело
- **form**: map сериализует результат в URL-encoded тело

---

## Ошибки

По умолчанию `ApigateError` возвращается как `text/plain`.
Полный runnable пример: `cargo run --example errors`.

Для единого JSON-формата можно задать глобальный рендерер
(он применяется и к pipeline, и к proxy/runtime ошибкам вроде 502/504):

```rust
fn render_error(err: apigate::ApigateFrameworkError) -> axum::response::Response {
    match &err {
        ApigateFrameworkError::Pipeline(ApigatePipelineError::InvalidJsonBody(details)) => {
            eprintln!("[apigate][invalid_json_body] details={details}");
            let body = serde_json::json!({
                "error": {
                    "code": "invalid_json_payload",
                    "message": "invalid json payload",
                }
            });
            return (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response();
        }
        _ => {
            if let Some(details) = err.debug_details() {
                eprintln!("[apigate][debug] code={} details={details}", err.code());
            }
        }
    }

    let body = serde_json::json!({
        "error": {
            "code": err.code(),
            "message": err.user_message(),
        }
    });
    (err.status_code(), axum::Json(body)).into_response()
}

let app = apigate::App::builder()
    .error_renderer(render_error)
    // ...
    .build()?;
```

`ApigateFrameworkError` нормализован по `code` (`err.code()`):
- `bad_request`
- `unauthorized`
- `forbidden`
- `payload_too_large`
- `unsupported_media_type`
- `bad_gateway`
- `gateway_timeout`
- `internal`

Также есть внутренние коды из `ApigateCoreError` и `ApigatePipelineError`
(например `invalid_header_name`, `invalid_json_body`, `request_body_too_large`).

Если нужно логировать низкоуровневую причину (не отдавая её клиенту),
используй `err.debug_details()`.

Ошибки конфигурации при сборке приложения (например, незарегистрированный backend/policy
или невалидный upstream URI) возвращаются из `.build()` как `ApigateBuildError`.

Из `before` / `map` можно вернуть полностью кастомный ответ:

```rust
#[apigate::hook]
async fn auth(ctx: &mut apigate::PartsCtx) -> apigate::HookResult {
    if ctx.header("authorization").is_none() {
        return Err(apigate::ApigateError::from_response((
            http::StatusCode::UNAUTHORIZED,
            axum::Json(serde_json::json!({
                "error": {
                    "code": "auth_missing_token",
                    "message": "missing authorization header"
                }
            })),
        )));
    }
    Ok(())
}
```

Удобный sugar для JSON:

```rust
#[derive(serde::Serialize)]
struct ErrBody {
    code: &'static str,
    message: String,
}

return Err(apigate::ApigateError::json(
    http::StatusCode::UNAUTHORIZED,
    &ErrBody {
        code: "auth_missing",
        message: "missing token".into(),
    },
));
```

Ещё короче для частых статусов:

```rust
return Err(apigate::ApigateError::unauthorized_json(&ErrBody {
    code: "auth_missing",
    message: "missing token".into(),
}));
```

Доступные sugar-методы:
- `ApigateError::bad_request_json(...)`
- `ApigateError::unauthorized_json(...)`
- `ApigateError::forbidden_json(...)`

---

## Runtime observability (`tracing`)

По умолчанию runtime observer apigate **выключен** (минимальный overhead в hot path).

Если нужно эмитить built-in runtime events через `tracing`:

```rust
let app = apigate::App::builder()
    .mount_service(sales::routes(), ["http://127.0.0.1:8081"])
    .enable_default_tracing()
    .build()?;
```

Observer можно явно выключить после условной конфигурации:

```rust
let app = apigate::App::builder()
    .mount_service(sales::routes(), ["http://127.0.0.1:8081"])
    .disable_runtime_observer()
    .build()?;
```

`enable_default_tracing()` эмитит структурированные runtime-события:
- старт запроса
- выбор backend
- ошибки pipeline / dispatch
- успех/ошибка upstream с latency

Ожидаемые клиентские ошибки (`4xx`) в default tracing observer пишутся на `info`, внутренние/серверные (`5xx`) — на `warn`.
Обычные успешные события (`request started`, `backend selected`, `upstream succeeded`) пишутся на `debug`.

Настройка уровней и формата выполняется в приложении через `tracing-subscriber`:

```rust
use tracing_subscriber::{EnvFilter, fmt};

fn init_tracing() {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info,apigate=debug"));

    fmt()
        .with_env_filter(filter)
        .with_target(true)
        .compact()
        .init();
}
```

Полный контроль (аналогично `error_renderer`) через `.runtime_observer(...)`:

```rust
fn observe(event: apigate::RuntimeEvent<'_>) {
    use apigate::RuntimeEventKind;

    match event.kind {
        RuntimeEventKind::PipelineFailedFramework { error } => {
            tracing::warn!(
                target: "app::gateway",
                service = event.service,
                route = event.route_path,
                code = error.code(),
                status = error.status_code().as_u16(),
                details = ?error.debug_details(),
                "pipeline failed"
            );
        }
        RuntimeEventKind::UpstreamFailed {
            backend_index,
            error,
            upstream_latency,
        } => {
            tracing::warn!(
                target: "app::gateway",
                service = event.service,
                route = event.route_path,
                backend_index,
                error = ?error,
                latency = ?upstream_latency,
                "upstream failed"
            );
        }
        _ => {}
    }
}

let app = apigate::App::builder()
    .mount_service(sales::routes(), ["http://127.0.0.1:8081"])
    .runtime_observer(observe)
    .build()?;
```

Для outer middleware (`tower-http::TraceLayer`, CORS, compression, timeout и т.д.)
используй API на уровне роутера:

```rust
use tower_http::trace::TraceLayer;

let app = apigate::App::builder()
    .mount_service(sales::routes(), ["http://127.0.0.1:8081"])
    .build()?
    .with_router(|r| r.layer(TraceLayer::new_for_http()));

apigate::run(listen, app).await?;
```

Если нужен полный manual-контроль, можно забрать роутер:

```rust
let router = apigate::App::builder()
    .mount_service(sales::routes(), ["http://127.0.0.1:8081"])
    .build()?
    .into_router();

let router = router.layer(TraceLayer::new_for_http());
apigate::run_router(listen, router).await?;
```

`hyper-util` тоже имеет внутренние transport/pool/connect логи. Их лучше включать только для диагностики:

```sh
RUST_LOG=info,apigate=debug,hyper_util::client::legacy=debug cargo run --example logging
```

Внутренний tracing самого `hyper` в 1.x нестабилен и требует отдельные feature/cfg flags, поэтому apigate не включает его по умолчанию.

---

## Инъекция параметров в `hook` / `map`

Макрос анализирует типы параметров и генерирует код извлечения:

| Тип | Источник | Пример |
|---|---|---|
| `&mut PartsCtx` | Контекст запроса | `ctx: &mut PartsCtx` |
| `&mut RequestScope` | Прямой доступ к scope | `scope: &mut RequestScope` |
| `&T` | `scope.get::<T>()` — shared state / per-request данные | `config: &AuthConfig` |
| `&mut T` | `scope.get_mut::<T>()` — только из local | `state: &mut Counter` |
| `T` (owned в hook) | `scope.take::<T>()` — local, fallback clone из shared | `path: SaleIdPath` |
| `T` (первый owned в map) | Входные данные (json/query/form) | `input: PublicBuy` |

Все параметры опциональны.

**Ограничения:** `&mut PartsCtx` / `&mut RequestScope` — макс. по одному; `&mut T` — макс. один и нельзя совмещать с `&T`; `&mut RequestScope` нельзя совмещать с `&T` / `&mut T`.

---

## Таймауты

| Метод | Дефолт | Описание |
|---|---|---|
| `.request_timeout(Duration)` | 30s | Полное время upstream-запроса. 504 при превышении |
| `.connect_timeout(Duration)` | 5s | TCP handshake к backend'у |
| `.pool_idle_timeout(Duration)` | 90s | Время жизни idle-соединений в connection pool |

---

## Политики

Политика = routing (какие backend'ы) + balancing (какой конкретно). Дефолт: `NoRouteKey` + `RoundRobin`.

```rust
.policy("sticky_sales", apigate::Policy::header_sticky("x-user-id"))
.policy("sticky_by_id", apigate::Policy::path_sticky("id"))
```

Встроенные пресеты:
- `Policy::header_sticky("x-user-id")` = `HeaderSticky + ConsistentHash`
- `Policy::path_sticky("id")` = `PathSticky + ConsistentHash`
- `Policy::consistent_hash()`
- `Policy::least_request()`
- `Policy::least_time()`
- `Policy::round_robin()`

Приоритет: атрибут маршрута > политика сервиса > дефолтная.

---

## Маршрутизация (routing)

Определяет набор кандидатов и опциональный affinity key для sticky sessions.

| Стратегия | Описание |
|---|---|
| `NoRouteKey` | Все backend'ы, без аффинности. **Дефолт** |
| `HeaderSticky::new("header")` | Affinity key из заголовка |
| `PathSticky::new("param")` | Affinity key из path-параметра `{param}` шаблона маршрута |

### Кастомная стратегия

```rust
use apigate::routing::{RouteStrategy, RouteCtx, RoutingDecision, AffinityKey, CandidateSet};

struct CookieSticky(&'static str);

impl RouteStrategy for CookieSticky {
    fn route<'a>(&self, ctx: &RouteCtx<'a>, _pool: &'a BackendPool) -> RoutingDecision<'a> {
        let affinity = ctx.headers.get("cookie")
            .and_then(|v| v.to_str().ok())
            .and_then(|c| c.split(';').map(str::trim)
                .find(|s| s.starts_with(self.0))
                .and_then(|s| s.split('=').nth(1)))
            .map(AffinityKey::borrowed);

        RoutingDecision { affinity, candidates: CandidateSet::All }
    }
}
```

**`RouteCtx`**: `service`, `prefix`, `route_path`, `method`, `uri`, `headers`.

**`RoutingDecision`**: `affinity: Option<AffinityKey>`, `candidates: CandidateSet` (`All` | `Indices(&[usize])`).

---

## Балансировка (balancing)

Выбирает конкретный backend из кандидатов.

| Стратегия | Описание |
|---|---|
| `RoundRobin::new()` | Циклический перебор. **Дефолт** |
| `ConsistentHash::new()` | Jump consistent hash по affinity key (xxh3). Без ключа — round-robin |
| `LeastRequest::new()` | Наименьшее число in-flight запросов |
| `LeastTime::new()` | Наименьшая EWMA-латентность |

Все балансировщики lock-free (атомарные операции).

### Кастомный балансировщик

```rust
use apigate::balancing::{Balancer, BalanceCtx, StartEvent, ResultEvent};

struct MyBalancer;

impl Balancer for MyBalancer {
    fn pick(&self, ctx: &BalanceCtx) -> Option<usize> {
        // ctx.candidate_len(), ctx.candidate_index(nth), ctx.affinity
        Some(ctx.candidate_index(0)?)
    }

    fn on_start(&self, _event: &StartEvent) {}        // опционально
    fn on_result(&self, _event: &ResultEvent) {}       // опционально
}
```

**`BalanceCtx`**: `service`, `affinity`, `pool`, `candidates`, `candidate_len()`, `candidate_index(nth)`, `candidate_backend(nth)`, `is_candidate(idx)`.

**`ResultEvent`**: `service`, `backend_index`, `status: Option<StatusCode>`, `error: Option<ProxyErrorKind>`, `head_latency: Duration`.

---

## Custom State

```rust
let app = apigate::App::builder()
    .state(DbPool(pool.clone()))
    .state(AuthConfig { jwt_secret: "...".into() })
    // ...
```

Доступ в хуках через `&T`:

```rust
#[apigate::hook]
async fn auth(ctx: &mut apigate::PartsCtx, config: &AuthConfig) -> apigate::HookResult {
    // config из shared state, zero-copy
    Ok(())
}
```

State хранится в `Extensions` внутри state роутера и передаётся в `RequestScope` по ссылке — **без per-request clone**. `scope.get::<T>()` читает shared-ссылку. `scope.insert()` / `scope.take()` работают с per-request хранилищем.

---

## Производительность

* Без `json/query/form` — body проксируется без чтения (streaming)
* `json = T` без `map` — валидация + passthrough оригинального тела
* State: shared `Extensions` по ссылке, 0 heap-аллокаций для read-only доступа
* Pipeline: path + hooks + body в одном `Box::pin`
* Route meta: индекс в таблице метаданных (`usize`) вместо `Arc<RouteMeta>` в request path
* HTTP-клиент: `TCP_NODELAY`, connection pooling, keep-alive
* `request_timeout``504 Gateway Timeout`
* Балансировщики lock-free (atomic counters)