A3S Gateway documentation
A3S Gateway 文档
Install, configure, extend, and benchmark the AI Native Traffic Layer.
安装、配置、扩展并测试 AI Native Traffic Layer。
Covers released 1.0.x behavior. The current package release is 1.0.13.
记录已发布的 1.0.x 行为,当前软件包版本为 1.0.13。
Documentation versions
文档版本
Gateway documentation follows the same stable and development-channel model as A3S Cloud. The selected version stays visible in the navigation and version switches preserve the current section.
Gateway 文档采用与 A3S Cloud 一致的稳定版和开发通道模型。导航栏始终显示当前版本,切换版本时会保留正在阅读的章节。
- v1.0Stable稳定版
- Released 1.0.x behavior and operator contracts. This is the default, indexable route.
- 已发布的 1.0.x 行为和运维契约。这是默认且可被索引的路由。
- nextDevelopment开发通道
- Forward-looking documentation under active development. It is not release evidence.
- 持续更新的前瞻文档,不作为版本已交付的证据。
The registry, Cargo major/minor series, routes, and section parity are checked before deployment. See the 发布前会检查版本注册表、Cargo 主次版本、路由和章节一致性。查看 product roadmap产品路线图 for maturity and promotion gates. 了解成熟度与晋级门槛。
Runtime model
运行时模型
Gateway binds listeners, matches routes, applies local policy, selects healthy backends, and relays HTTP, SSE, WebSocket, gRPC, TCP, or UDP. Every request uses one validated runtime snapshot.
Gateway 绑定监听器、匹配路由、执行本地策略、选择健康后端,并转发 HTTP、SSE、WebSocket、gRPC、TCP 或 UDP。每个请求只使用一个已校验的运行时快照。
Request path
请求路径
Routing, authentication, admission limits, health-aware selection, streaming bounds, retries before response start, and telemetry.
路由、鉴权、准入限制、健康感知选择、流式边界、响应开始前重试和遥测。
Snapshot activation
快照激活
ACL or A3S Cloud supplies complete desired state. Gateway validates and compiles it before an atomic swap.
ACL 或 A3S Cloud 提供完整期望状态。Gateway 在原子切换前完成校验和编译。
Rejected changes
拒绝无效变更
A failed bind, invalid middleware, missing reference, or rejected reload leaves the previous runtime active.
监听失败、无效中间件、引用缺失或 reload 被拒绝时,原有运行时继续工作。
Feature status and roadmap
特性状态与路线图
The status column separates shipped Gateway behavior from local foundations, experiments, and planned cross-product work. A foundation is usable inside Gateway but does not claim that the complete A3S Cloud workflow is finished.
状态列把已交付的 Gateway 行为与本地基础、实验能力和计划中的跨产品工作分开。“Gateway 基础已提供”表示本地部分可用,但不代表完整 A3S Cloud 工作流已经完成。
The core data plane is suitable for controlled production with a validated capacity envelope and rollback path. Managed recovery, long-duration reliability, independent security review, and production adoption evidence remain Enterprise GA gates.
核心数据平面适用于具备容量验证和回滚路径的受控生产环境。受管恢复、长期可靠性、独立安全审查和真实生产采用证据仍是 Enterprise GA 门槛。
Current delivery
当前交付
| AREA | STATUS | Current scope当前范围 |
|---|---|---|
| Protocol plane | Available已提供 | HTTP/1.1, HTTP/2, SSE, WebSocket, gRPC, TCP, UDP, TLS, verified HTTP/HTTPS upstreams, trailers, backpressure, independent stream bounds, and bounded drain.HTTP/1.1、HTTP/2、SSE、WebSocket、gRPC、TCP、UDP、TLS、上游证书校验、trailer、背压、独立流式边界和有界排空。 |
| Routing and backends | Available已提供 | Host/path/method/header/SNI rules, priority, four balancing strategies, active/passive health, circuit state, sticky sessions, failover, mirroring, and static revision weights.Host/路径/方法/header/SNI 规则、优先级、四种均衡策略、主动/被动健康、熔断状态、粘性会话、故障转移、镜像和静态版本权重。 |
| Middleware | Available已提供 | Fifteen built-in authentication, admission, retry, header, body, compression, and network policy types plus typed Rust MiddlewareRegistry extensions.15 种内置鉴权、准入、重试、header、body、压缩和网络策略,以及类型化 Rust MiddlewareRegistry 扩展。 |
| Configuration lifecycle | Available已提供 | Standalone ACL and Cloud-managed modes, fail-closed validation, listener reconciliation, atomic activation, prior-runtime retention, exact readiness, and optional durable managed-state recovery.Standalone ACL 与 cloud-managed 模式、失败关闭校验、监听器协调、原子激活、保留上一运行时、精确就绪状态和可选持久受管状态恢复。 |
| Managed OpenAI paths | Gateway foundationGateway 基础已提供 | Models, chat, completions, embeddings, grants, RPM/burst/concurrency admission, rewriting, request/attempt identity, health-aware targets, and pre-response fallback run locally.模型列表、Chat、Completions、Embeddings、授权、RPM/突发/并发准入、重写、请求/尝试身份、健康目标和响应前 fallback 在本地运行。 |
| Observability | Available已提供 | Terminal JSON access logs, W3C/B3 trace intake, W3C propagation, Prometheus metrics, service latency/TTFT/pressure signals, and bounded labels.终端 JSON 访问日志、W3C/B3 trace 接收、W3C 传播、Prometheus 指标、服务延迟/TTFT/压力信号和有界标签。 |
| Usage spool | Gateway foundationGateway 基础已提供 | Prompt-free request/attempt records with integrity, bounded capacity, restart recovery, ordered replay, contiguous acknowledgement, reclamation, and compaction.不含 prompt 的请求/尝试记录,支持完整性、容量边界、重启恢复、有序重放、连续确认、空间回收和压缩。 |
| Machine Node API | Available已提供 | Bounded machine-only health, readiness, metrics, version, snapshot apply, and usage acknowledgement endpoints. It is not an operator web platform.受限的机器专用健康、就绪、指标、版本、快照应用和用量确认端点;它不是运维 Web 平台。 |
| Providers and delivery | Available已提供 | File watch, HTTP discovery, Docker labels, optional Kubernetes Ingress, verified macOS/Linux/Windows installers, archives, Cargo, Homebrew, Docker, and Helm.文件监听、HTTP 发现、Docker 标签、可选 Kubernetes Ingress,以及校验过的 macOS/Linux/Windows 安装器、归档、Cargo、Homebrew、Docker 和 Helm。 |
| Standalone autoscaling | Experimental实验性 | Local and Kubernetes Scale adapters exist and stay isolated from Cloud-managed mode; real-cluster, Box recovery, and versioned-idempotency proof remain open.本地与 Kubernetes Scale 适配器已存在,并与 cloud-managed 模式隔离;真实集群、Box 恢复和版本化幂等验证仍待完成。 |
| Automatic gradual rollout | Not available未提供 | rollout {} is rejected. Standalone mode can use static revision weights; managed rollout decisions belong to A3S Cloud.Gateway 会拒绝 rollout {}。Standalone 可使用静态版本权重;受管发布决策属于 A3S Cloud。 |
Planned work and open proof
计划能力与待完成验证
| TRACK | STATUS | Remaining outcome待完成结果 |
|---|---|---|
H0.2 managed targets | Joint proof联合验证 | Process loss, redelivery, stale/digest/expiry rejection, certificate replacement, and mixed Gateway versions with A3S Cloud.与 A3S Cloud 联合验证进程丢失、重新投递、过期/摘要/有效期拒绝、证书替换和混合 Gateway 版本。 |
I0.2b authorization | Planned计划中 | Trusted token accounting, grant budgets and reconciliation, the Cloud policy compiler, expiry, revocation, fallback, and mixed-version conformance.可信 token 计量、授权预算与对账、Cloud 策略编译器,以及过期、撤销、fallback 和混合版本一致性。 |
I0.2c usage delivery | Planned计划中 | Authenticated batches, highest-contiguous ACK, production upload, explicit gap recovery, and Cloud ledger ingestion.认证批次、最高连续 ACK、生产上传、显式缺口恢复和 Cloud 用量账本接入。 |
H0.3-H0.5 topology | Planned计划中 | Target-generation identity, removal before termination, bounded drain, rolling replacement, node loss, revision skew, and degraded readiness across replicas.目标代际身份、终止前移除、有界排空、滚动替换、节点丢失、版本偏差和多副本降级就绪。 |
| Enterprise GA | Promotion gate晋级门槛 | Dedicated-hardware capacity envelopes, long-duration soak and fault-injection evidence, operator runbooks, an independent security review, and representative production adoption.专用硬件容量边界、长期稳定性与故障注入证据、运维手册、独立安全审查和代表性生产采用案例。 |
| Standalone scaling | Experimental proof实验验证 | Validate Kubernetes Scale on a real cluster, close Box executor recovery, and add versioned idempotency.在真实集群验证 Kubernetes Scale,完成 Box 执行器恢复并增加版本化幂等。 |
| Performance evidence | Planned evidence计划验证 | Profile scheduler and upstream-pool costs on dedicated hardware, add payload, upstream-latency, connection-count and long-stream variants, then set regression thresholds after stable runs.在专用硬件上分析调度器和上游连接池成本,增加 payload、上游延迟、连接数和长流变体,并在数据稳定后设置回归阈值。 |
A0 / C0 AI protocols | Contract first合同优先 | Native MCP or remote Agent traffic waits for versioned identity, authorization, affinity, resumption, cancellation, drain, discovery, bounds, telemetry, and recovery contracts. A2A has no committed milestone.原生 MCP 或远程 Agent 流量要先定义版本化身份、授权、亲和、恢复、取消、排空、发现、边界、遥测和恢复合同;A2A 尚无承诺里程碑。 |
Install
安装
The installers detect the platform, download a release archive, verify its published SHA-256 checksum and binary version, then replace the user-local executable.
安装脚本会检测平台、下载发布归档、校验已发布的 SHA-256 和二进制版本,然后替换用户目录中的可执行文件。
macOS / Linux
shellcurl --proto '=https' --tlsv1.2 -LsSf https://a3s-lab.github.io/Gateway/install.sh | shWindows PowerShell
powershell[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
irm https://a3s-lab.github.io/Gateway/install.ps1 | iexCargo / Homebrew
shellcargo install a3s-gateway
# or
brew install a3s-lab/tap/a3s-gateway~/.local/bin/a3s-gateway on macOS/Linux and %LOCALAPPDATA%\A3S\bin\a3s-gateway.exe on Windows.默认位置:macOS/Linux 为 ~/.local/bin/a3s-gateway,Windows 为 %LOCALAPPDATA%\A3S\bin\a3s-gateway.exe。First route
第一条路由
Start an HTTP backend on port 8000, save the following file as gateway.acl, validate it, and start Gateway.
先在 8000 端口启动一个 HTTP 后端,把下面的内容保存为 gateway.acl,完成校验后启动 Gateway。
gateway.aclmode { kind = "standalone" }
entrypoints "web" {
address = "127.0.0.1:8080"
}
routers "models" {
rule = "PathPrefix(`/v1`)"
service = "models"
entrypoints = ["web"]
middlewares = ["rate-limit"]
}
middlewares "rate-limit" {
type = "rate-limit"
rate = 60
burst = 10
}
services "models" {
load_balancer {
strategy = "least-connections"
request_timeout = "30s"
stream_idle_timeout = "5m"
stream_total_timeout = "60m"
servers = [{ url = "http://127.0.0.1:8000" }]
}
}shella3s-gateway validate --config gateway.acl
a3s-gateway config --config gateway.acl summary
a3s-gateway --config gateway.acl
curl http://127.0.0.1:8080/v1/modelsACL configuration model
ACL 配置模型
ACL is the configuration source of truth. References are resolved before listeners change. A router must name an existing service, middleware, and entrypoint; every service needs at least one server or revision target.
ACL 是配置事实源。Gateway 会在监听器变化前解析全部引用。路由必须引用已有的服务、中间件和 entrypoint;每个服务至少要有一个 server 或 revision target。
| BLOCK | Purpose作用 | Important fields关键字段 |
|---|---|---|
mode | Select local ACL ownership or Cloud snapshots.选择本地 ACL 或 Cloud 快照作为状态来源。 | kind = "standalone" | "cloud-managed" |
entrypoints | Bind HTTP, TCP, or UDP listeners and optional TLS.绑定 HTTP、TCP 或 UDP 监听器及可选 TLS。 | address, protocol, tls, max_connections |
routers | Match traffic and assemble service plus policy references.匹配流量并组合服务与策略引用。 | rule, service, entrypoints, middlewares, priority |
middlewares | Define reusable HTTP request/response policy.定义可复用的 HTTP 请求/响应策略。 | type plus type-specific fields |
services | Define targets, balancing, time bounds, health, failover, and mirroring.定义目标、负载均衡、时间边界、健康检查、故障转移和镜像。 | load_balancer, revisions, mirror, failover |
observability | Configure access logs, metrics, and trace propagation.配置访问日志、指标和 trace 传播。 | access_log, metrics, tracing |
management | Bind the bounded machine-only Node API.绑定受限的机器专用 Node API。 | address, path_prefix, auth, IP, TLS/mTLS |
managed | Set Cloud identity, durable snapshot state, and usage spool.设置 Cloud 身份、持久快照状态和用量 spool。 | gateway_id, state_file, usage_spool |
managed.gateway_id cannot include local routers, services, middleware, inference policy, dynamic providers, rollout, or local scaling. A3S Cloud delivers traffic state as a complete managed snapshot.模式隔离:设置 managed.gateway_id 的 cloud-managed 启动配置不能包含本地路由、服务、中间件、推理策略、动态 provider、rollout 或本地扩缩容。流量状态由 A3S Cloud 以完整受管快照下发。Routing and services
路由与服务
Rules support host, path prefix, method, header, and SNI conditions. Explicit priority decides evaluation order. The selected service uses round-robin, weighted, least-connections, or random balancing after health filtering.
规则支持 Host、PathPrefix、Method、Header 和 SNI 条件。显式 priority 决定评估顺序。选中的服务在健康过滤后使用 round-robin、weighted、least-connections 或 random 均衡。
routing.aclrouters "chat" {
rule = "Host(`api.example.com`) && PathPrefix(`/v1/chat`)"
service = "models"
entrypoints = ["web"]
middlewares = ["auth", "limits"]
priority = 100
}request_timeoutbounds connection and first response.request_timeout限制连接和首响应等待。stream_idle_timeoutresets when a body chunk arrives.stream_idle_timeout在收到 body chunk 后重新计时。stream_total_timeoutis an absolute operation bound.stream_total_timeout是整个操作的绝对上限。- Retry and failover are allowed only before the upstream response starts.重试和故障转移只允许发生在上游响应开始前。
Middleware pipeline
中间件处理链
The router's middlewares list is ordered. Request hooks run left to right and may short-circuit with a response. Response header and bounded body hooks run right to left. One middleware definition can be reused by multiple routers.
路由的 middlewares 列表有顺序。请求钩子从左到右执行,并可直接返回响应中止后续流程;响应 header 和有界 body 钩子从右到左执行。一个中间件定义可以被多个路由复用。
policy.aclrouters "models" {
rule = "PathPrefix(`/v1`)"
service = "models"
entrypoints = ["web"]
middlewares = ["auth", "limits", "security-headers"]
}
middlewares "auth" {
type = "api-key"
header = "X-API-Key"
keys = ["replace-me"]
}
middlewares "limits" {
type = "body-limit"
max_body_bytes = 8388608
}
middlewares "security-headers" {
type = "headers"
response_headers = [{ name = "X-Content-Type-Options", value = "nosniff" }]
}Built-in catalog
内置目录
| TYPE | Effect作用 | Configuration配置项 |
|---|---|---|
api-key | Require one configured key in a request header.要求请求 header 携带已配置的 key。 | header, keys |
basic-auth | Validate HTTP Basic credentials.校验 HTTP Basic 凭据。 | username, password |
jwt | Validate a Bearer JWT.校验 Bearer JWT。 | value secret |
forward-auth | Ask an external authorization endpoint before proxying.转发前调用外部鉴权端点。 | forward_auth_url, response headers |
rate-limit | Apply process-local token-bucket admission.执行进程内 token-bucket 准入。 | rate, burst |
rate-limit-redis | Apply shared Redis-backed admission; requires the redis Cargo feature.执行 Redis 共享准入;需要 redis Cargo feature。 | redis_url, rate, burst |
cors | Handle origins, methods, headers, and preflight caching.处理 origin、method、header 和预检缓存。 | allowed_origins, methods, headers, max_age |
headers | Set request and response headers.设置请求和响应 header。 | request_headers, response_headers |
strip-prefix | Remove a configured literal or one-segment wildcard prefix.移除配置的固定前缀或单段通配前缀。 | prefixes |
ip-allow | Allow configured IP addresses or CIDR ranges.允许指定 IP 或 CIDR 范围。 | allowed_ips |
retry | Retry eligible failures before response start.在响应开始前重试符合条件的失败。 | max_retries, retry_interval_ms |
circuit-breaker | Open after failures and probe after cooldown.失败达到阈值后打开,冷却后探测恢复。 | failure, cooldown, success thresholds |
body-limit | Reject request bodies above a byte limit.拒绝超过字节上限的请求 body。 | max_body_bytes |
compress | Negotiate and apply Brotli, gzip, or deflate to eligible responses.为符合条件的响应协商并执行 Brotli、gzip 或 deflate。 | type = "compress" |
TCP filter | Filter TCP source IPs at the entrypoint; it is not an HTTP pipeline hook.在 entrypoint 过滤 TCP 来源 IP;它不是 HTTP 中间件钩子。 | tcp_allowed_ips |
Custom middleware in Rust
使用 Rust 自定义中间件
An embedded deployment can implement the public Middleware trait, register the value by a stable router-facing name, and create Gateway with Gateway::with_middlewares. Custom and built-in middleware can appear in the same ordered route list.
嵌入式部署可以实现公开的 Middleware trait,用稳定的路由引用名称注册实例,再通过 Gateway::with_middlewares 创建 Gateway。自定义和内置中间件可以出现在同一个有序路由列表中。
src/main.rsuse a3s_gateway::{Gateway, Middleware, MiddlewareRegistry, RequestContext, Result};
use a3s_gateway::config::GatewayConfig;
use async_trait::async_trait;
use http::{request::Parts, HeaderValue, Response};
struct TenantPolicy;
#[async_trait]
impl Middleware for TenantPolicy {
async fn handle_request(
&self,
request: &mut Parts,
_context: &RequestContext,
) -> Result<Option<Response<Vec<u8>>>> {
request.headers.insert(
"x-policy-source",
HeaderValue::from_static("tenant-policy"),
);
Ok(None)
}
fn name(&self) -> &str { "tenant-policy" }
}
#[tokio::main]
async fn main() -> Result<()> {
let config = GatewayConfig::from_file("gateway.acl").await?;
let mut middleware = MiddlewareRegistry::new();
middleware.register("tenant-policy", TenantPolicy)?;
let gateway = Gateway::with_middlewares(config, middleware)?;
gateway.start().await?;
gateway.wait_for_shutdown().await;
Ok(())
}gateway.aclrouters "models" {
rule = "PathPrefix(`/v1`)"
service = "models"
entrypoints = ["web"]
middlewares = ["tenant-policy", "rate-limit"]
}
# No middlewares "tenant-policy" block: Rust supplies that name.Gateway::with_middlewares. ACL snapshots can reorder registered names; the standalone binary does not load dynamic libraries or Wasm plugins.扩展模型:在 Gateway::with_middlewares 前注册类型化 HTTP 中间件。ACL 快照可以重排注册名称;独立二进制不加载动态库或 Wasm 插件。Performance measurements
性能测量与结果
Criterion measures in-process operations. The proxy matrix measures every supported data-plane traffic type against NGINX on the same runner and shared local upstreams.
Criterion 测量进程内操作;代理矩阵在同一 runner 和共享本地上游上,对 A3S Gateway 支持的所有数据面流量类型与 NGINX 进行测试。
Feature-free HTTP, finite SSE, and standalone OpenAI profiles use the startup-bound direct relay and one sharded Hyper upstream pool. A startup-bound single backend also skips backend-operation counters because routing, scaling, concurrency, and telemetry consumers are absent. TLS, HTTP/2, gRPC, feature-bearing streaming, upgrade, and layer-4 profiles retain their protocol-specific paths.
无附加功能的 HTTP、有限 SSE 和独立 OpenAI 场景使用启动时绑定的直达转发与同一组分片 Hyper 上游连接池。启动时绑定的单一后端还会跳过后端操作计数,因为路由、扩缩容、并发控制和遥测均不会读取该计数;TLS、HTTP/2、gRPC、带功能的流式、升级和四层场景保留各自的协议路径。
Internal Criterion baseline
内部 Criterion 基线
| OPERATION | INPUT | MEDIAN | 95% CI |
|---|---|---|---|
| route / highest exact host | 1,000 routes | 147.1 ns | 146.9-147.3 ns |
| route / unknown exact host | 1,000 routes | 51.6 ns | 51.5-51.6 ns |
| middleware | 10 entries | 965.1 ns | 964.7-965.4 ns |
| ACL parse | 300 services/routes | 4.926 ms | 4.921-4.928 ms |
Same-host protocol matrix
同机协议矩阵
| TRAFFIC / WORKLOAD | LOAD | A3S GATEWAY RATE / P50 / P90 / P99 | NGINX RATE / P50 / P90 / P99 | A3S ÷ NGINX RATE / P99 |
|---|---|---|---|---|
| Loading published measurements... | ||||
OpenAI JSON and stream rows enable bounded A3S request validation and the shared streaming response relay while NGINX performs transport-only forwarding. Use those rows to quantify feature cost, not as an equivalent policy comparison.
OpenAI JSON 与流式场景中,A3S 开启有界请求校验并使用共享流式响应转发,NGINX 仅执行传输转发。这两行用于量化功能成本,不作为等价策略能力对比。
This run used the same image and EPYC 9V74 as the preceding 68c5d2d run. The WebSocket-only change measured +0.03%, while eight other non-gRPC A3S medians stayed between -1.2% and -0.4%. Untouched gRPC varied by -19% and NGINX HTTP/2 also moved materially, exposing shared-runner protocol noise. Treat this as regression evidence, not an isolated speedup or capacity forecast.
本次与紧邻的 68c5d2d 运行使用相同镜像和 EPYC 9V74。仅 WebSocket 的改动测得 +0.03%,其余 8 个非 gRPC A3S 中位数在 -1.2% 至 -0.4%;未受改动的 gRPC 波动 -19%,且 NGINX HTTP/2 也有明显变化,说明共享 runner 存在协议级噪声。本数据仅作为回归证据,不作为单项加速或容量预测。
Criterion JSON / Protocol matrix JSON / Workflow run / Benchmark source
A3S Cloud integration
A3S Cloud 集成
The Node API exposes health, metrics, version, and managed snapshot operations. A3S Cloud provides deployment, rollout, tenancy, and the long-term usage ledger.
Node API 提供健康、指标、版本和受管快照操作;A3S Cloud 提供部署、发布、租户和长期用量账本。
| OWNER | Responsibilities职责 |
|---|---|
| A3S Gateway | Listeners, protocol fidelity, routing, middleware, health, request limits, local snapshot activation, telemetry, and bounded durable usage records.监听器、协议一致性、路由、中间件、健康检查、请求限制、本地快照激活、遥测和有界持久用量记录。 |
| A3S Cloud | Human operations, tenants, credential catalogs, deployment, workload placement, desired replicas, production rollout, audit views, and the long-term usage ledger.人员运维、租户、凭据目录、部署、工作负载放置、期望副本、生产发布、审计视图和长期用量账本。 |
Troubleshooting
故障排查
| SYMPTOM | Check检查项 |
|---|---|
| unknown middleware | Define the name in ACL, or register it before Gateway::with_middlewares in an embedded binary.在 ACL 中定义该名称,或在嵌入式二进制中于 Gateway::with_middlewares 前完成注册。 |
| reload rejected | Run a3s-gateway validate. Check missing references, listener conflicts, middleware feature flags, service time bounds, and mode isolation.运行 a3s-gateway validate,检查引用缺失、监听冲突、中间件 feature、服务时间边界和模式隔离。 |
| 502 / 504 | Check backend URL and health, certificate trust, request_timeout, idle/total stream bounds, and whether every target is unavailable.检查后端 URL 与健康状态、证书信任、request_timeout、流式 idle/total 边界,以及是否所有目标都不可用。 |
| Redis limiter rejected | Build with --features redis and validate redis_url. Gateway fails closed when the type is configured without the feature.使用 --features redis 构建并校验 redis_url。配置了类型但未启用 feature 时 Gateway 会失败关闭。 |