routers

package
v1.833.310 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Package routers @APIVersion 1.70.0 @Title Hanzo Cloud RESTful API @Description Swagger Docs of Hanzo Cloud Backend API @Contact cloud@hanzo.ai @SecurityDefinition AccessToken apiKey Authorization header @Schemes https,http @ExternalDocs Find out more about Hanzo Cloud @ExternalDocsUrl https://hanzo.ai/cloud

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AliasFilter added in v1.833.247

func AliasFilter(c *zip.Ctx) error

AliasFilter rewrites a request that names an alias (models.yaml alias_of) to name the id the alias stands for, before anything reads the model: routing, the gate, the plan limits, the handler and the ledger all see that id, so an alias is served and billed as it. /v1/decisions is left alone: its handler resolves an alias after the credential. So is a body with a Content-Encoding: this runs ahead of every credential, and reading a coded body's model means decoding it for a sender nobody has authenticated. Its model reaches the handler as sent.

func AuthAvailableFilter added in v1.832.10

func AuthAvailableFilter(c *zip.Ctx) error

AuthAvailableFilter refuses every request while this process cannot validate a bearer token, and is the ONE place that decision is made.

It runs BEFORE any filter that reads a token (AutoSignin, Balance, Tenant, Authz), so no downstream code ever sees the difference between "this token is invalid" and "no cert was ever established". That difference is the whole point: the two look identical at a token-parsing call site, and treating the second as the first is what once left the service Running and answering 401 to everything, including free routes, with no crashloop and no alert to catch it.

503, not 401. A 401 says "your credential is wrong" to a caller whose credential is fine, invites a client to discard a good token and re-authenticate, and reads as normal traffic on every dashboard. 503 says the honest thing — the service cannot answer right now — and Retry-After tells a client when to come back.

It is deliberately NOT a readiness probe. A probe failure would take the pod out of service entirely; identity being briefly unreachable should cost the requests that need identity, not the process. Requests are refused while it is down and served again on the first attempt that succeeds, with no restart.

func AuthzFilter

func AuthzFilter(c *zip.Ctx) error

func AutoRouteFilter added in v1.833.237

func AutoRouteFilter(c *zip.Ctx) error

AutoRouteFilter resolves a completion that names the virtual `auto`/`zen-router` model to the SKU that will serve it, before BalanceGateFilter reads the request. The gate and the plan limits then price and admit that SKU, never the virtual id. See controllers.RouteAuto. A body with a Content-Encoding is left as sent, as AliasFilter leaves it: the handler resolves its `auto` once it has authenticated the sender, and the gate meanwhile prices the virtual id, which has no price and so is never free.

func BalanceGateFilter

func BalanceGateFilter(c *zip.Ctx) error

BalanceGateFilter is a BeforeRouter filter that checks whether the requesting user has a positive Commerce balance before allowing paid API requests to proceed. It runs after AutoSigninFilter (which sets session users for legacy auth paths) and handles its own user resolution for JWT and IAM API key auth paths.

Posture: fail-CLOSED on balance, never on money. When billing is unconfigured (no gate) or the billing subject cannot be identified, the request passes to the downstream auth/controller layer, which re-checks (identity is that layer's job). When the subject IS identified, a positive spendable balance is REQUIRED: a known-insufficient balance is denied 402 (add credits), and a balance that cannot be verified is denied 503 (retry) — both deny. AI is prepaid; a billing-backend outage becomes a retryable 503, never free inference.

func CacheControlFilter

func CacheControlFilter(c *zip.Ctx) error

CacheControlFilter adds Cache-Control headers to prevent caching of sensitive API endpoints This ensures that sensitive data (like passwords, user chats, messages) are not cached by intermediary proxies, SSL terminators, or browsers

func CorsFilter

func CorsFilter(c *zip.Ctx) error

func Dialect added in v1.833.251

func Dialect(c *zip.Ctx) error

Dialect answers /v1/decisions in the decision service's words, whichever layer answers — one that wrote its refusal, and one that returned it. A rate limit, a quota, a balance gate and an authorization filter each write a refusal of their own before the handler runs; every one of them leaves as {"error":{"code","message"}}, a 402, 429 or 529 carries Retry-After and Retry-After-Ms, and every answer carries X-Request-Id — the caller's own, or a fresh one the handler also forwards to the service. controllers.Restate is the rule; the handler and the ZAP twins apply the same one.

func Document added in v1.832.46

func Document(app *zip.App) map[string]any

Document is everything this service serves, as one OpenAPI 3.1 document.

The result is deterministic: it reads the route table and two package-level tables, and nothing here reads the clock, the environment, or a random source.

func GetOrg added in v1.804.1

func GetOrg(c *zip.Ctx) string

GetOrg resolves the organization for data-scoping in filters from the VERIFIED request principal — never a raw client header.

On the direct (non-gateway) ingress the X-Org-Id header is fully client-controlled, so trusting it would let any caller act as any org (cross-tenant read/write + billing attribution). It is honored ONLY when it matches the authenticated principal's own org, or the principal is a global admin (cross-org platform access). A non-admin can never escape their own org via a header; an unauthenticated caller's header is ignored entirely.

Behind the gateway the injected X-Org-Id equals the JWT owner, so this resolves identically — the gateway path is unaffected.

func GetSessionUser

func GetSessionUser(c *zip.Ctx) *iam.User

GetSessionUser is the identity a FILTER sees, and it is the same identity the handler sees: the request's verified IAM token, read by the one function that reads it. Filters and handlers cannot disagree about who is calling.

It used to read a per-pod in-memory session store, and its own comment recorded the cost: the store is filled by a session hook that does not run when the embedded binary serves these routes, so this answered nil on every request and the filters billed and rate-limited by the raw key instead. A store that is nil in production is not an identity source. The token always travels with the request.

func GetTenantOrgID

func GetTenantOrgID(c *zip.Ctx) string

GetTenantOrgID returns the org from IAM web.

func GetTenantProjectID

func GetTenantProjectID(c *zip.Ctx) string

GetTenantProjectID returns the project ID from IAM web.

func GetTenantUserID

func GetTenantUserID(c *zip.Ctx) string

GetTenantUserID returns the user ID from IAM web.

func HstsFilter

func HstsFilter(c *zip.Ctx) error

HstsFilter adds HTTP Strict Transport Security header to HTTPS responses This ensures browsers only access the website using HTTPS

func InitBalanceGate

func InitBalanceGate()

InitBalanceGate reads Commerce connection parameters from app config and creates the balance gate. Must be called once during startup. If Commerce is not configured, the gate is not created and BalanceGateFilter is a no-op. IAM connection parameters are NOT read here: key resolution goes through the one resolver (controllers.GetUserByAccessKey), which owns that config.

func InitTierCache

func InitTierCache()

InitTierCache reads Commerce connection parameters from app config and creates the tier cache. Must be called once during startup.

The cache exists when a tier can be READ, by either route: the reader a co-resident host installs, or the HTTP endpoint a standalone ai is given. Keying its existence on the endpoint alone would leave a host that installs a reader and configures no endpoint able to read every tier and asking for none. With neither, there is nothing to ask and DefaultTierFunc falls back to env-var overrides or TierZenFree.

func InstallFilters added in v1.822.2

func InstallFilters(app *zip.App)

InstallFilters puts the request chain in front of every route, in this order.

It installs onto the APP it is handed, and there is no once-guard. There was one, and it was a leftover from the router being a package variable: guarding a per-app installation with a process-wide Once means the SECOND app built in a process gets no chain at all — no auth, no balance gate, and no recover. One process only ever serves one app, so production never saw it; a test that builds a second one did, as a panic escaping a chain that was never installed.

EACH ONE DECIDES WHETHER TO CONTINUE, and says so by returning c.Continue() or not. That used to be implied: a filter wrote a response and returned, and the router inferred a refusal from the fact that something had been written. The refusals are now the shape of the code.

There is no "after" list. Recording used to be two filters — one before the router, one after the handler — passing a username between them through a request parameter; it is one middleware holding a local across the handler. Cookie rewriting was the other after-filter, and it went with the session store it patched.

Two filters are gone entirely, and both were doing somebody else's job:

  • Auto-signin accepted an MD5 of clientId:clientSecret, or HTTP Basic against the configured pair, and minted an IsAdmin identity into a per-pod in-memory store. IAM mints credentials; this service reads the one presented.
  • Static served a landing folder, the admin bundle and /storage from a path taken off the URL, and rewrote main.<hash>.js on the way out. Static content is ingress and the static plugin. Every route here is /v1.

There are no path-rewriting filters either. Two used to lead the chain: /v1/cloud/* → /v1/* rewrote EVERY route into a second address, and /v1/iam/* did the same for four account endpoints. Between them a single endpoint answered at three URLs, each one a place a policy could be applied inconsistently. Resources live at exactly one address, generated from the table in resources.go.

func Patterns added in v1.833.89

func Patterns(app *zip.App) map[string][]string

Patterns is the live route table as path → verbs.

zip declares routes as a flat list of (method, pattern); this is the same information keyed the way its callers ask it — "what does this address serve" — which is the question both the OpenAPI document and the filter-path test have. It is derived, never maintained, so it cannot claim a verb the app does not serve.

func PrometheusFilter

func PrometheusFilter(c *zip.Ctx) error

func RateLimitFilter

func RateLimitFilter(c *zip.Ctx) error

RateLimitFilter holds every /v1 request to a rate and a quota.

EVERY request, because the ceilings are asked about the CALLER rather than about the credential they happened to carry — see limitSubject. The exceptions are the paths isRateLimitExempt names and anything outside /v1, which is not this API.

func Record added in v1.833.89

func Record(c *zip.Ctx) error

Record attributes each request to the principal that made it, and writes the row after the handler has answered.

It was TWO filters passing a username between them through a request parameter, because a before-the-router filter and an after-the-handler filter have no other way to share. One middleware holds it in a local across the handler: nothing to name, nothing to look up, nothing to lose.

func Recovered added in v1.833.89

func Recovered(c *zip.Ctx) (err error)

Recovered turns a panic into a 500, so one request cannot take anything else with it.

It is FIRST in the chain, which is deliberate: it has to cover the filters as well as the handlers. A gate that panics while deciding whether to admit a request is the worst place to lose the process, because it happens before anything has been served.

This is not new behaviour, it is behaviour that had to be moved. The router this service used to run recovered in two places of its own — once around the filter chain and once around handler dispatch — so a nil dereference anywhere in ~360 handlers became a 500 and the process carried on. zip installs no recovery (its own examples show the app adding one), and under fasthttp an unrecovered panic takes the connection. Registering the routes natively removed the old router and its recover with it; this is the recover, in one place, where the chain is built.

The body is the house envelope and says nothing else. A panic is ours, not the caller's: the stack goes to the log where an engineer reads it, and the caller gets a 500 they can retry rather than a description of our internals.

func Register added in v1.833.89

func Register(app *zip.App)

Register binds every /v1 route this service serves onto the app, and installs the filter chain around them. Routes are explicit; there is no annotation-based registration.

ONE entry point, called by ai.App. It used to be an init() writing onto a package-level router, so the table existed the moment the package was imported — before anything could say what it should be registered ON, and with no way for a test to ask for a clean one.

THE FILTERS GO ON FIRST, and that is not cosmetic: the router walks its stack in registration order, so a filter added after a route never runs before it. The chain would still be installed, still be tested, and simply not be in front of anything.

func TenantContextFilter

func TenantContextFilter(c *zip.Ctx) error

TenantContextFilter captures IAM identity context for downstream scoping and observability. The org is taken from the VERIFIED principal (GetOrg), NOT the raw X-Org-Id header: on the direct ingress that header is client-controlled, so storing it verbatim would let any caller spoof a tenant. GetOrg honors the header only for the principal's own org (or a global admin), so the stored org is always the caller's real tenant.

func TrafficTapFilter added in v1.817.0

func TrafficTapFilter(c *zip.Ctx) error

TrafficTapFilter is a BeforeRouter tap that folds each genuine inbound /v1 API request into the in-process traffic aggregate (object.GlobalTraffic), keyed by the country the host stated for the caller (controllers.Country) and a coarse service class derived from the path. It powers the public world.hanzo.ai live- traffic globe.

PRIVACY (load-bearing): it reads ONLY the country/region geo headers. It never reads CF-Connecting-IP or any client IP, never hashes anything, and hands the aggregate nothing but (country, region, service) — Record has no IP parameter to pass one to. It is a pure side effect: it never writes a response, never blocks, never errors, and returns immediately, so its position in the filter chain cannot affect any request's outcome.

Types

type BalanceGate

type BalanceGate struct {
	// contains filtered or unexported fields
}

BalanceGate enforces a positive spendable balance before paid requests. The balance itself lives in the shared object.BalanceLedger — the ONE source of truth also used by the controller debit path to reserve (before a request) and settle (after). Reading the ledger here makes the gate reservation-aware and reflects local settles immediately, so the cache window can never serve a stale-positive balance after the funds are spent. The gate adds only its own freshness scheduling (async refresh from Commerce) and identity resolution.

type Doc added in v1.832.7

type Doc struct{ Summary, Description string }

Doc is one operation's prose: the opening sentence, and the whole comment.

type Quota added in v1.833.72

type Quota struct {
	// contains filtered or unexported fields
}

Quota admits requests while a key is inside its tier's ceiling for every period.

func NewQuota added in v1.833.72

func NewQuota(tierFunc func(string) Tier, cleanupInterval time.Duration) *Quota

NewQuota creates a Quota that evicts keys untouched for a full month every cleanupInterval. The tierFunc callback resolves an API key to its Tier; pass nil to always use TierZenFree.

func (*Quota) Metrics added in v1.833.72

func (q *Quota) Metrics() (allowed, denied uint64)

Metrics reports the running allowed and denied counts.

func (*Quota) Spend added in v1.833.72

func (q *Quota) Spend(key string, now time.Time) (ok bool, refused string, until time.Time)

Spend charges one request to key and reports whether every period admitted it.

A refusal names the period that refused and the instant it next rolls, which is what a caller needs to know to come back. A REFUSED request is charged to nothing: one exhausted ceiling must not go on burning down the longer ones, which would let a caller who is out for eight hours lose their whole month.

On a host with shared counts (object.SetCounters) the windows are kept there, so every replica counts one caller together and a restart forgets nothing.

func (*Quota) Stop added in v1.833.72

func (q *Quota) Stop()

Stop ends the cleanup goroutine.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter tracks per-key rate limiters with automatic cleanup of stale entries.

func InitRateLimiter

func InitRateLimiter(tierFunc func(string) Tier) *RateLimiter

InitRateLimiter creates the global rate limiter. Must be called once during startup (before web.Run). Returns the instance so the caller can call Stop() on shutdown.

It says what it armed, and says it by READING tierLimits. Boot used to print the tiers as prose from where it called this, and prose does not follow a table: the line named a free tier of 10/min next to two tiers that no longer exist, and a reader took it for the configuration. A boot line is evidence of what was armed, so it comes from the thing that armed it.

func NewRateLimiter

func NewRateLimiter(tierFunc func(string) Tier, cleanupInterval time.Duration) *RateLimiter

NewRateLimiter creates a RateLimiter that starts a background goroutine to evict stale entries every cleanupInterval. The tierFunc callback resolves an API key to its Tier; pass nil to always use TierZenFree.

func (*RateLimiter) Admit added in v1.833.279

func (rl *RateLimiter) Admit(lanes []address.Bucket) bool

Admit charges one request to the lanes it is counted on, narrowest first, each at its tier's rate times the lane's scale, and reports whether every lane had room.

A WIDER LANE IS SPENT ONLY BY WHAT A NARROWER ONE ADMITTED. The walk stops at the first lane that refuses, so one /64 hammering past its own ceiling spends nothing of the /48 its neighbours share: a site is emptied by sixteen callers' worth of admitted traffic, never by one caller's refusals.

One request in Metrics, however many lanes it is counted on.

On a host with shared counts (object.SetCounters) every lane is a bucket every replica spends from, so a restart or a second replica hands nobody a fresh rate.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(apiKey string) bool

Allow checks whether a request from the given API key should be permitted. It returns true if the request is within the rate limit.

func (*RateLimiter) Metrics

func (rl *RateLimiter) Metrics() (allowed, denied uint64)

Metrics returns the current rate limit hit/pass counters.

func (*RateLimiter) Open added in v1.833.184

func (rl *RateLimiter) Open(apiKey string) bool

Open reports whether a lane still has room, spending nothing.

It is what a caller this process cannot yet NAME has to clear before the round trip that names them. Allow would spend a token on the address lane and then the named request would spend a second one from its own; Open asks the same question and leaves the accounting to whichever lane ends up carrying the request.

func (*RateLimiter) RetryAfter

func (rl *RateLimiter) RetryAfter(lanes []address.Bucket) int

RetryAfter returns the number of seconds until every lane has a token again: the longest wait among them.

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop terminates the background cleanup goroutine.

type Response

type Response struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`
	Data   any    `json:"data"`
	Data2  any    `json:"data2"`
}

type Tier

type Tier string

Tier represents an API usage tier with associated rate limits. All tiers follow the "zen-*" naming convention as the canonical identifier.

const (
	TierZenFree       Tier = "zen-free"
	TierZenPro        Tier = "zen-pro"
	TierZenTeam       Tier = "zen-team"
	TierZenEnterprise Tier = "zen-enterprise"
	TierZenCustom     Tier = "zen-custom"
)

func DefaultTierFunc

func DefaultTierFunc(key string) Tier

DefaultTierFunc resolves a rate-limit key to a Tier. The key is whatever limitSubject named the caller: an IAM org slug when a billing subject resolved, a confirmed page key, or a digest of the address the caller arrived from when neither. The tier is the caller's plan as commerce records it, and nothing else:

  1. Commerce tier cache -- backed by async lookups to Commerce billing API (GET /v1/billing/tier?user=<org>). On cache hit, the cached tier is returned immediately. On cache miss, TierZenFree is returned and a background goroutine populates the cache so the next request uses the correct tier.
  2. TierZenFree -- default when no cache entry exists.

There is no operator override: a tier names a recorded subscription, so no configuration can grant one.

This function never blocks on network I/O. Commerce lookups happen asynchronously; the worst case is that a new org's first few requests are rate-limited at the free tier until the cache is populated.

type TierCache

type TierCache struct {
	// contains filtered or unexported fields
}

TierCache caches apiKey-to-tier mappings resolved from Commerce. Stale entries (older than tierCacheTTL) are lazily ignored on read and periodically evicted by a background goroutine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL