跪拜 Guibai
← Back to the summary

Three-Layer Contract: Shape, Semantics, and Failure in Alioth's Error Handling

proto Contract: Validation Annotations, Error Codes, and "Copy as Interface"

Alioth Tech Notes · Issue 23 · API Design / Error Handling Repository: https://github.com/aide-family/moon | Live Demo: https://web.alioth.asia/

Introduction

An API contract actually has three layers: shape (field length, range), semantics (whether this role can use it, whether this package includes it), and failure expression (what to return when something goes wrong). Mixing all three together leads to two typical symptoms: annotations written but never taking effect, and the frontend receiving a 400 with no idea what to do. Alioth uses buf.validate for shape, business use cases for semantics, and merr for expression. This post explains how the three connect.

1. Annotations on the proto don't take effect automatically

int32 page = 1 [(buf.validate.field).int32 = {gte: 0}];
int32 page_size = 2 [json_name = "pageSize", (buf.validate.field).int32 = {gte: 0, lte: 100}];

The annotations look intuitive, but there's a pitfall you must know about:

// protoValidator connects the buf.validate constraints on the proto to the Kratos middleware.
// Generated code does not invoke the validator; without this step, all min_len, min_items, lte annotations won't take effect.
func protoValidator() middleware.Middleware {
    return kvalidate.Validator(func(req any) error {
        msg, ok := req.(proto.Message)
        if !ok { return nil }
        return protovalidate.Validate(msg)
    })
}

Once the middleware is attached (once for HTTP and once for gRPC), page_size > 100 will be rejected as a 400. Many projects write a wall of buf.validate annotations that never work because they're missing this assembly line.

2. Two layers of validation, each handles half

Proto can handle mechanical constraints: length, range, required, enum validity. It can't handle things that depend on the database:

for _, level := range in.Levels {
    item, err := rulebook.dictionaries.GetAlertDictionary(ctx, namespaceUID, level.LevelUID)
    if err != nil { return err }
    if item.Type != "ALERT" || item.Status != "ACTIVE" {
        return merr.Invalid("invalid request")
    }
}

"This level dictionary exists and is enabled" can only be known by querying the database. So both layers must exist, and they should not overlap: proto handles "shape", business handles "state". Conversely, the business layer also can't assume "proto validation passed" — internal gRPC calls, scheduled tasks, and CLI invocations might not go through the HTTP middleware. So you'll still see length checks in business code, with comments like:

// maxClusterName stays consistent with proto validation to avoid writes of overlong names via paths that bypass HTTP.

The two constants must stay in sync; that's the cost. The payoff is that data entering through any door is safe.

3. The seven reasons of merr

Client(message)          // 400 CLIENT
Invalid(message)         // 400 INVALID
Unauthenticated(message) // 401 UNAUTHENTICATED
Forbidden(message)       // 403 FORBIDDEN
NotFound(message)        // 404 NOT_FOUND
Conflict(message)        // 409 CONFLICT
Server(message)          // 500 SERVER

Client and Invalid are both 400, which might seem redundant. The difference is in semantics: Client means "the request itself is wrong" (missing parameters, malformed format), while Invalid means "the request is well-formed but violates domain rules" (an unapproved command, a badly written expression).

This distinction isn't for looks; it's for callers to make decisions. The evaluator in Issue 05 uses it that way:

// Client errors like invalid expressions are rule configuration problems, not data source unavailability:
// don't write back the batch, keep trying in the next round, and recovery happens when the user fixes the rule.
if merr.IsInvalid(err) { return err }

If every 400 were called Client, the evaluator would have to choose between "treat it as a data source failure" or "ignore it entirely" — both are wrong. The first value of error classification is to let upstream handle it automatically, not to show it to a human.

4. Unified error format

Interfaces that go through proto are output by Kratos's default encoder; bare HTTP handlers that don't use proto (like the migration package download) have a separate one:

func writeHTTPError(w http.ResponseWriter, err error) {
    status := kerrors.FromError(err)
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.WriteHeader(int(status.Code))
    json.NewEncoder(w).Encode(map[string]any{
        "code": status.Code, "reason": status.Reason,
        "message": status.Message, "metadata": status.Metadata,
    })
}

Each of the four fields has a purpose: code goes to the network layer and logs, reason for machine classification, message for the user, and metadata for structured supplements. metadata has a real usage — when sending an email verification code too frequently:

return merr.ClientWithMetadata("send code too frequently", map[string]string{
    "retryAfterSeconds": strconv.Itoa(seconds),
})

The frontend reads retryAfterSeconds directly to render a countdown, rather than regex-extracting a number from the copy. Anything the frontend needs for logic should go into metadata, not into message.

5. Frontend: status code drives behavior, message drives copy

if (response.status === 401 && retry && !staysOnAuthForm(path)) {
    if (await refreshAccessToken()) { return request(path, init, false) }
    clearSession()
}
if (response.status === 403 && !allowForbidden && window.location.pathname !== "/forbidden") {
    window.location.assign("/forbidden")
}

The copy layer is a giant mapping table:

const messageKeys: Record<string, string> = {
  "member limit reached": "error.memberLimit",
  "package is no longer available": "error.packageUnavailable",
  "kubeconfig credential was rejected by the cluster": "error.clusterCredentialRejected",
  ...
}

That's what "copy as contract" means. The benefits are concrete: no need to maintain a huge error code catalog, logs and tickets can be read directly to understand the failure cause, and internationalization is centralized in the mapping table. The costs are equally concrete:

Alioth accepts this cost because in the platform's early stage, what matters most is "errors are readable", not "error codes are stable". The right evolution path is to add metadata.code for high-risk errors, so the frontend matches by code first and uses message only as a fallback — rather than continuing to stuff semantics into copy.

6. A few real pitfalls

  1. Upstream status codes must not be passed through. From Issue 14: a cluster returning 401 means "your kubeconfig is bad", but if the platform passes it through, the browser will clear the login state; a 403 will make the frontend jump to a completely unrelated permission page. So the mapping layer must translate upstream semantics into the platform's own semantics.
  2. Network failures should be wrapped as 502. A failed fetch only gives Failed to fetch; if it isn't wrapped, the list page will stuff that raw English text into the content area. Wrapping it as 502 lets the page render a standard error page.
  3. allowForbidden is an explicit whitelist. Without this parameter, 403 always redirects — a "safe by default" choice: a new endpoint that forgets to handle 403 shows users a permission page rather than a blank area.
  4. proto validation errors also go through the same format. The middleware returns a kratos error: code is 400, reason might be the validator's built-in reason, and message is the validation failure detail. The frontend maps it by message just like the others; if it doesn't match, it shows the raw text and doesn't crash.

7. How to verify

pkg/merr/merr_test.go uses table-driven tests to assert the code and reason of the seven error types, plus the mutual exclusivity of IsInvalid/IsConflict/IsNotFound — these mappings are the easiest thing to drift silently during refactors. Manual verification:

git clone https://github.com/aide-family/moon.git && cd moon
make dev-up
open http://127.0.0.1:8080

Request a pagination endpoint with pageSize=1000 and you should get a 400 (proto annotation working); hit the same endpoint without a token and you should get a 401 and the frontend triggers one refresh; access it with an account that lacks alert:read permission and you should get a 403 and be redirected to the permission page.

Conclusion

The stability of an API contract comes from three separate concerns: shape goes to proto annotations and takes effect in the assembly layer, semantics go to business use cases, and failures go to a unified reason + message. "Copy as interface" is a deliberate trade-off — it makes errors immediately readable at the cost of making messages a field that can't be casually changed. Knowing what you're paying is better than pretending there's no cost.


Next: Frontend design system — brand tokens and shadcn/ui in practice.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

星云PLUS团队 1 likes

Beyond the shape and state layers, there is a category of constraints that neither side can accommodate: the precision of numeric fields. buf.validate can write gte/lte, but it cannot handle cross-field relationships such as "amount's precision must match currency" or "tax must accumulate positively when taxInclusive is false". These are neither length limits nor database state checks, so they fit better at the business use-case layer, and error codes can then land on Invalid rather than Client. As for the cost of "two constants must stay in sync" mentioned in the article, you can try generating both the proto and the business layer from the same contract constants, turning drift from a manual review issue into a codegen-time problem.