Repository navigation
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The customer, organization, caller kind, server side mark and request id
of a request were stored under keys that only the API package could see,
so a controller in another package had to go through `Server` to read
them. This PR moves those keys, with their setters and readers, into a
package of their own that any controller can import. Nothing changes at
run time and the API spec does not change.
## How it works
```
request
│
├─ withRequestID ───────────> reqctx.WithRequestID
├─ auth middleware ─────────> reqctx.WithCustomer, WithOrganization,
│ WithServerSide, WithKind
└─ scheduled delivery ──────> reqctx.WithCustomer, WithServerSide, WithKind
│
v
context of the request
│
┌────────────────────────────────────┴───────────────┐
v v
api.CustomerFrom, KindFrom, ... reqctx.IdentityFrom
(one-line delegates, every caller nil without a customer, else
in internal/api is unchanged) AppID, Caller, Kind, ServerSide
```
The new package has an `AGENTS.md` (its rules, each with a command that
shows when it is broken) and a `CLAUDE.md` that only links it. `reqctx`
imports only `auth` and `routing`. `IdentityFrom` has no production
caller yet: the session controllers read it in a later PR of this
series.
## What differs from the base
| Base in `internal/api` | Now | What differs |
| --- | --- | --- |
| `customerContextKey`, `organizationContextKey`,
`serverSideContextKey`, `kindContextKey`, `requestIDContextKey` |
`customerKey`, `organizationKey`, `serverSideKey`, `kindKey`,
`requestIDKey` in `reqctx` | The names |
| `CustomerFrom`, `OrganizationFrom`, `ServerSideFrom`, `KindFrom`,
`RequestIDFrom` | Same names in `reqctx`, delegates in `api` | The body
differs only in the key name |
| `CallerFrom` | `reqctx.CallerFrom`, delegate in `api` | Nothing |
| `context.WithValue(ctx, <key>{}, v)` in `server.go`, `requestid.go`,
`scheduled_delivery.go` | `reqctx.With*(ctx, v)` | Same value, same
order |
| `context.WithValue` and `huma.WithValue` on these keys in 18 test
files | `reqctx.With*` | Assertions are unchanged |
The keys for the request's public key, the actor, the logged app and the
request failure stay in `internal/api`, since this PR does not need them
elsewhere.
## Tests
| Test | Defect it catches |
| --- | --- |
| `TestIdentityFromIsNilWhenCustomerIsMissingOrEmpty` | A request with
no customer gets an empty identity instead of none |
| `TestIdentityFromReadsAllRequestIdentityFields` | A setter and a
reader use different keys, or a field of `Identity` is not filled |
| `TestServerSideFromReadsBackFalse` | A setter ignores its argument, so
a device passes for a backend |
| `TestRequestIDFromRoundTrips` | The request id is stored under one key
and read under another |
| `TestOrganizationFromRoundTripsIndependently` | The organization
shares a key with the customer or the request id |
| `ScheduledTasksSuite/TestADeliveryRunsAsItsTasksOwnerServerSide`
(integration) | A scheduled delivery runs as the user's device. Before
this PR no test in that suite failed when the mark was false. |
<details><summary>Mutations and commands</summary>
Each mutant was applied, tested and restored in turn, and a test failed
for every one:
- Each of the five setters writes under another key, or ignores its
value.
- Each reader returns nothing, or the opposite. `CustomerFrom` accepts
an empty customer.
- The guard of `IdentityFrom` is off, or always on. Each field of
`Identity` is dropped, and `ServerSide` is read from the caller.
- Each delegate in `internal/api` calls another reader, or returns the
zero value.
- Each argument in the auth middleware, `withRequestID` and
`scheduledOwnerContext` is swapped or emptied.
Two mutants needed more than the first run: an empty organization in the
middleware is caught by `TestAccountSuite`, and a false server side mark
in `scheduledOwnerContext` is caught only by the new test.
```
go test ./internal/api/reqctx ./internal/api
go build ./... && go vet ./... && go vet -tags integration ./internal/... ./cmd/...
go run ./cmd/openapi && git diff --exit-code api/openapi.yaml
go test -tags integration ./internal/api -run '^(TestActivitySuite|TestAuditSuite|TestAuthorizationsSuite|TestFloorControlSuite|TestOAuthClientDataKeysSuite|TestAgentTeamsSuite|TestUsageIdentitySuite|TestProxiedUsageSuite|TestShippedUsageSuite|TestKnowledgeFilesSuite|TestScheduledTasksSuite)$'
```
`gofmt -l` names `dispatch_channel_test.go` and
`session_create_unit_test.go`, as it does on the base.
The whole integration run is not done here.
</details>
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The session controllers need to return API errors, but the error types
live in a package they cannot import. This PR moves the types to a small
package of their own and leaves aliases behind, so existing code keeps
working. Nothing changes for a caller: statuses, codes, messages and the
API spec are the same.
## How it works
```text
internal/api internal/api/apierr (new)
type APIError = apierr.APIError ----> APIError, ErrorType,
(alias: the same type) ErrorResponse, ErrorDetail,
newAPIError, notFound, ... the type/status/code table
(constructors stay for now) Of
an error or a response body
│
├─ refusalText (session socket) ─┐
└─ noteRefusals (activity count) ─┴─> apierr.Of(v)
├─ APIError -> it, true
├─ type embedding one -> it, true
│ (moneyAnswer)
└─ anything else -> false
```
| Change | Result | Test |
| --- | --- | --- |
| `refusalText` uses `apierr.Of` | a socket frame keeps the refusal's
own words, also for a refusal with headers |
`TestRefusalTextReturnsTheMessageOfARefusalWithHeaders`,
`TestRefusalTextReturnsTheMessageOfAPlainRefusal` |
| `noteRefusals` uses `apierr.Of` | a refusal an operation returns is
still counted with its code |
`TestARefusalAnOperationReturnedIsCountedWithItsCode` (integration) |
| `Of` in `apierr` | matches an `APIError` and a type embedding one,
nothing else | `TestOfReturnsTheFailureATypeEmbeds`,
`TestOfReturnsFalseForAnythingElse` |
| Aliased `ErrorType*` constants | each type keeps its wire name |
`TestEveryErrorTypeIsSentUnderItsOwnName` |
| Types moved | `api/openapi.yaml` has no diff | `go run ./cmd/openapi`
|
## Why every match changes in this PR
The moved type has an unexported method that three places matched on. Go
treats an unexported method as a different one in each package, so a
match left behind would compile and never succeed. All three now call
`apierr.Of`.
## What differs from the moved code
| Symbol | Difference from the base |
| --- | --- |
| `ErrorType`, its constants, `errorTypes`, `errorDocs`, `APIError` and
its other methods, `ErrorDetail` | none |
| `(ErrorType).Schema` | calls `schema.NamedEnum`, which `namedEnum`
delegates to |
| `SomethingWentWrong`, `(*ErrorResponse).TransformSchema` | the
constant is exported; `api` keeps `somethingWentWrong` with its value |
| `apiError()` | its comment names `Of` instead of `noteRefusals` |
| `newAPIError`, `statusError` (stay in `api`) | read the moved table
through `ErrorType.Code` and `TypeOfStatus` instead of looping over it |
| `TestEveryErrorTypeIsAnsweredWithItsOwnStatus` | moved to `apierr`
with its assertions, in a suite; it builds the `APIError` directly |
| `authorizations_test.go` | expects the full documentation URL as text,
since `errorDocs` is now unexported in another package |
## Why `Code` and `TypeOfStatus` are exported
The constructors move in the next piece, so for now two of them need to
read a table that has already moved. These two lookups keep one copy of
the table. The next piece can unexport them.
<details><summary>Mutations and commands</summary>
A left-over `interface{ apiError() APIError }` match in `internal/api`,
tried before the switch to `Of`: it compiles and answers false for both
`APIError` and `moneyAnswer`, and both refusal text tests fail.
45 mutations, all caught:
- `Of` (5): matching `APIError()` instead of `apiError()` fails both
refusal text tests; matching only the `APIError` type fails the one with
headers; the wrong answer, value or ok fails
`TestOfReturnsTheFailureATypeEmbeds` or the stream socket tests.
- `ErrorType.Code` (3), `TypeOfStatus` (3), `newAPIError` (2),
`statusError` (2): inverted match, wrong row, wrong answer for an
unknown value, dropped message.
- `Status` (2), `DocURL`, `MarshalJSON`, `Error`.
- The spec (3): the `ErrorType` and `APIError` schemas and the 500 text
each change `openapi.yaml`.
- `refusalText` (4) and `noteRefusals` (3, with `TestActivitySuite`),
the old assertion included.
- Each of the 15 aliased constants, pointed at another type.
Commands, from `acceleration/`: `go build ./...`, `go vet ./...`, `go
vet -tags integration ./internal/... ./cmd/...`, `go run ./cmd/openapi
&& git diff --exit-code api/openapi.yaml`, `go test ./internal/api
./internal/api/...`, and `TestActivitySuite`, `TestAuthorizationsSuite`
and `TestAdmissionSuite` with `-tags integration`. All pass.
The integration suites not named here were not run locally.
</details>
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Do not merge yet: ship-feature is in progress.
createSessionis a controller since #2728, but it still reaches back intoServerthrough ten proxy methods. This branch gives session controllers a plain struct of six layers instead, and moves the helpers they share with other operations into their own packages. The API andopenapi.yamldo not change.It lands as 12 small PRs, one after another, into this branch. Tracking: AI-4467.
Gates for the merge into main
none (no migration, no flag, no behaviour change)
🤖 Generated with Claude Code