Skip to content

refactor(api): createSession as a controller - #2728

Merged
kanat merged 15 commits into
mainfrom
refactor/controller
Nov 30, 2026
Merged

kanat merged 15 commits into
mainfrom
refactor/controller

Conversation

@kanat

@kanat kanat commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Today every API operation is a method on Server, in one large package, and can reach everything the server holds. This PR shows what a controller looks like in the new layout and how it is registered, using one operation: createSession (POST /v1/agents/sessions). The API itself does not change, openapi.yaml is the same as on main.

How it works

The controller

Every operation becomes a struct that implements one interface:

type Controller[Input, Output any] interface {
	// Spec describes the operation without needing runtime dependencies.
	Spec() Spec
	Handle(ctx context.Context, in Input) (Output, error)
}

Spec says what the operation is and Handle does the work. A controller does not know about Server.

This is createSession, without the body of Handle:

type CreateSession struct {
	Deps Deps
}

func (CreateSession) Spec() endpoint.Spec {
	return endpoint.Spec{
		Name:              "createSession",
		Summary:           "Join a call as a voice agent",
		Description:       "The whole conversation runs here: ...",
		Status:            http.StatusCreated,
		StatusDescription: "The agent is in the call",
		Access:            endpoint.AccessClientAccessible,
		Errors: map[int]string{
			http.StatusBadRequest: "",
			http.StatusConflict:   "A session with that id already exists, ...",
			// 401, 403 and 404 as well
		},
	}
}

func (c CreateSession) Handle(ctx context.Context, in *payload.CreateSessionInput) (*payload.CreateSessionOutput, error) {
	// the same steps as before, in the same order
}

The input and output are structs with a Body field, because Huma reads the request body from a field with that name. Path, query and header parameters go next to it:

type CreateSessionInput struct {
	Body CreateSessionRequest
}

type CreateSessionOutput struct {
	Body Session
}

What the spec is for

The spec keeps everything we declare about an operation in one place, next to its code. It is plain data with no Huma types in it, and it can be read without a running server, which is how openapi.yaml is generated.

Field What it is used for
Name, Summary, Description, Tags, Deprecated The operation in openapi.yaml, which the SDKs are generated from
Status, StatusDescription The status of a successful answer
Access Whether an end user's device may call it. An operation that does not say so is server-side only
Errors The errors we document. An empty string keeps the standard description
Events The events an operation can emit. This is a placeholder, nothing fills or reads it yet

How a controller is registered

Each feature has a routes.go with its paths:

func Register(api *humabind.API, deps controller.Deps) {
	humabind.Post(api, "/v1/agents/sessions", controller.CreateSession{Deps: deps})
}

newAPI in openapi.go wraps the Huma API once and adds the validators next to the middleware:

api := humabind.New(humachi.New(router, config))
api.UseMiddleware(nameHumaOperation)
api.UseMiddleware(s.requireStaffKey(api))
api.UseMiddleware(requireCustomer(api))
api.UseValidator(validators...)
openapi.go: sessions.Register(api, sessionDeps{server: s})
  -> sessions/routes.go: humabind.Post(api, path, CreateSession{Deps: deps})
       -> humabind: turns the Spec into a huma.Operation
            -> RegisterOperation: the validators, then CreateSession.Handle

humabind also has Get, Put, Patch and Delete.

How the request is checked

The checks from #2729 stay as they are, so createSession answers the same errors as on main:

request -> Huma decodes it and checks the field tags
        -> CreateSessionRequest.Resolve
        -> serverside tags (validateServerSideFields, 403)
        -> CreateSession.Handle
  • The validators are one list in internal/api/validate.go. The controllers get it from UseValidator, and the other operations from register, so neither can skip the serverside tags. UseValidator has to come before the operations, as UseMiddleware does. Today the list holds only validateServerSideFields.
  • Resolve is on the type in payload. Its rules read the caller, which only internal/api knows, so internal/api sets them in payload.CreateSessionProblems. This is a workaround, like Deps.

TestRequestsFollowTheValidationRules no longer needs a hook in production code. It reads the types of the request bodies from the schema registry of Huma. The registry does not hold path, query and header parameters, or whether Body is a pointer, so the new TestRequestStructsFollowTheValidationRules checks those in the source.

Dependencies (not final)

A controller gets its dependencies when it is constructed, as CreateSession{Deps: deps}.

The Deps interface in this PR is a workaround, please do not review it as the final design. createSession calls many helpers on Server, and Deps is the quick way to move those calls out of the controller. session_deps.go implements it by calling the existing helpers.

Dependencies do not have to look like this. Later they may return layers that several controllers can share, instead of one method for each helper createSession happens to need.

Folders

internal/api/
├─ endpoint/     Spec, Access and the Controller interface
├─ humabind/     turns a Spec into a Huma operation and registers it
├─ events/       placeholder for the events an operation can emit
├─ schema/       types several operations share (Greeting, FloorControl)
├─ sessions/
│  ├─ controller/create_session.go   CreateSession: Spec and Handle
│  ├─ controller/deps.go             Deps
│  ├─ payload/session.go             CreateSessionInput, CreateSessionOutput
│  └─ routes.go                      POST /v1/agents/sessions
└─ session_deps.go                   implements Deps with the Server

Changes

It is easier to review the commits one by one.

  • 38570a9bf only moves types. A controller in its own package cannot import internal/api without an import cycle, so the types it uses moved out, and internal/api keeps an alias for each one.
  • 55e8ce933 adds the new layout. This is the commit to read closely.
  • 4136c79e9 addresses the review: humabind.register is unexported and endpoint.go is now controller.go.
  • 3830ff94e keeps the request checks of AI-4429: standardize router API input validation #2729 after the rebase.
  • 81653ebd8, 14c5a659d and a408b0aad name those checks validators and list them in one place, in validate.go.
  • 52c472b2d passes that list to sessions.Register.
  • 140ccf9b4 makes Validator an interface and adds ValidateFunc, which turns a function into a Validator.
  • bb34d0716 makes a validator a plain function, ValidateFunc, and removes the Validator interface again.
  • 768d7ebfb adds humabind.New and UseValidator, so sessions.Register no longer takes the validators.
  • 9118cc0d8, 6161455f3 and 4f677c536 remove the global hook that only TestRequestsFollowTheValidationRules used, and add TestRequestStructsFollowTheValidationRules.

All the other operations stay where they are.

Validation

Check Result
go build ./..., go vet ./internal/api/..., also with -tags integration, at 4f677c536 pass
go test ./internal/api/... at 4f677c536 pass
go test -tags integration ./internal/api at 3830ff94e, before the validator commits 2 tests of TestResponsesAskedSuite fail because ffmpeg is not installed on my machine, and the same 2 fail on main (07fa7a972). No other test fails
go run ./cmd/openapi at 4f677c536 openapi.yaml is identical to main
75 requests to createSession (25 bodies, as an anonymous caller, a user and a backend), at 3830ff94e, before the validator commits the same answers as on main

TestCreateSessionRefusesItsRequestOverHTTP fails when createSession skips the serverside tags or Resolve. The existing HTTP tests in internal/api cover the rest.

What each new test in humabind_test.go catches
Defect Test
The status or the body is not passed through TestBodyControllerDecodesRequestAndWritesStatusAndResponse
A registered controller skips a validator, or they run out of order TestValidatorsRefuseInOrderBeforeTheController
A missing body reaches the controller TestBodyControllerRefusesMissingRequestBody
The envelope shows up in the OpenAPI schemas, or a described error loses its text TestBodyControllerUsesWireDTOComponentsInOpenAPI
A server-only operation is marked x-client-accessible TestAccessControlsClientAccessibleOpenAPIExtension
A typo in Access is accepted TestUnknownAccessPanicsAtRegistration
An error's status is lost TestControllerErrorSetsHTTPStatus
Path parameters do not reach the controller TestNonBodyControllerReceivesPathParametersDirectly

🤖 Generated with Claude Code

@github-actions github-actions Bot added the docs label Nov 30, 2026
kanat and others added 4 commits November 30, 2026 09:52
The types createSession takes and returns now live in sessions/payload,
since a controller in its own package cannot import internal/api without
an import cycle. The types other operations use too, such as Greeting,
are in schema. internal/api keeps an alias for each one, so no other code
changes and openapi.yaml stays the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createSession is the first operation in the new layout: a controller with
a Spec and a Handle method, its payload, and a routes.go that mounts it.
The controller gets what it needs through a Deps interface and no longer
sees the Server. The checks run in the same order and openapi.yaml stays
the same.

Spec.Events is only a placeholder, nothing fills or reads it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createSession's request is still refused by its Resolve and its serverside
tags, as #2729 made it. humabind runs the same check register does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat
kanat force-pushed the refactor/controller branch from 18abba6 to 3830ff9 Compare November 30, 2026 14:52
@kanat
kanat requested a review from aliev November 30, 2026 15:12
@kanat
kanat marked this pull request as ready for review November 30, 2026 15:38
@getstream-metis

Copy link
Copy Markdown

👋 Hi Kanat, want a second pair of eyes on this?

I'm Jeffery, Stream's review agent. I look for bugs, regressions, missing tests and slow paths, and I only post findings I've checked against the code.

  • Review this PR

Or comment /jeffery review. I'll stay quiet unless you ask.

kanat and others added 11 commits November 30, 2026 10:53
openapi.go now builds the humabind.API once, so every feature
registers its controllers on the same one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
register and humabind both run the list in interceptors.go before
the handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
They only check the input and may refuse it. The list now lives in
validate.go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
routes.go builds the humabind.API from them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ValidateFunc turns a function into a Validator, the way
http.HandlerFunc does. The test hook moves to humabind, because
validators now only run on requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operation argument had no reader and the interface had one
implementation, so the list now holds functions and needs no conversion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The API is wrapped once, in newAPI, and the validators are added next to
the middleware, so sessions.Register no longer takes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RegisterOperation keeps the request's type in the operation's Metadata,
and the test of the validation rules reads it from the registered
operations instead of setting a global hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No production code serves TestRequestsFollowTheValidationRules any more.
The registry holds the types of the bodies, so the test no longer checks
serverside parameters or a pointer body tagged required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This covers the two rules Huma's registry cannot: serverside parameters
and a pointer body tagged required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@kanat
kanat merged commit 417f2be into main Nov 30, 2026
13 checks passed
@kanat
kanat deleted the refactor/controller branch November 30, 2026 19:43
kanat added a commit that referenced this pull request Dec 1, 2026
`createSession` moved to a controller, but nothing told the next author
how to write one, and the root `AGENTS.md` still sent every new
operation to `register` and `policies.go`. An agent reading both
followed whichever it read first. Part of AI-4467.

## How it works

```
root AGENTS.md «HTTP API»
├─ new operation  -> acceleration/internal/api/AGENTS.md (controllers)
└─ legacy ops     -> register in validate.go (do not add more)
```

## Changes

| Change | Where |
| --- | --- |
| Controller guide: Spec fields, `Spec.Name` rule, `humabind.Option`,
wiring in `newAPI` after `UseValidator`, errors, validation checks,
testing via `RouterSuite` (#2728) |
`acceleration/internal/api/AGENTS.md` (+ `CLAUDE.md` -> `@AGENTS.md`) |
| `register`/`policies.go` marked legacy,
`endpoint.AccessClientAccessible` named | root `AGENTS.md` |
| `Deps` comment says it is a migration adapter, not the pattern |
`sessions/controller/deps.go` |

Facts the guide states that are easy to get wrong:

- `Spec.Events` is declared but no code reads it
(`humabind/humabind.go`, `operation()`).
- A validator only applies to controllers registered after
`UseValidator` (`humabind/humabind.go:54`, `openapi.go:359`).
- `APIError` constructors are unexported in `apierror.go`, so a
controller gets refusals from its deps until they move to a leaf
package.

## Validation

Docs and one comment only. `go build ./internal/api/...` and `gofmt`
pass.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants