Skip to content

feat(go)!: redesign HTTP serving API with genkithttp and genkithttp/exp - #7443

Merged
apascal07 merged 13 commits into
ap/go-v2from
ap/go-v2-http-api
Dec 5, 2026
Merged

apascal07 merged 13 commits into
ap/go-v2from
ap/go-v2-http-api

Conversation

@apascal07

@apascal07 apascal07 commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Redesigns Genkit Go v2 HTTP serving on standard net/http, targeting the v2 branch (ap/go-v2). Two packages replace genkit.Handler, genkit.HandlerFunc, plugins/server, the genkit/exp route builders, and core.ContextProvider: stable genkithttp and experimental genkithttp/exp (package genkithttpx). Genkit serves actions; routing, CORS, auth, and server lifecycle stay with the application's router and its middleware, so Chi, Gin, Echo, and http.ServeMux all mount Genkit routes without adapters. Also fixes the v1 wire protocol bugs and updates the JS streamFlow client SSE parser to handle comment and metadata lines.

One concrete handler per action, mounted on any router

Before:

mux := http.NewServeMux()
mux.HandleFunc("POST /story", genkit.Handler(storyFlow, genkit.WithContextProviders(authProvider)))
for _, r := range genkitx.AllAgentRoutes(g) {
	mux.HandleFunc(r.Pattern(), r.Handler())
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))

After:

mux := http.NewServeMux()
mux.Handle("POST /story", genkithttp.NewHandler(storyFlow))
for _, rt := range genkithttpx.AgentRoutes("/agents/chat", chatAgent) {
	mux.Handle(rt.Pattern(), rt.Handler)
}
log.Fatal(http.ListenAndServe("127.0.0.1:8080", requireAuth(mux)))

NewHandler returns a concrete *genkithttp.Handler (implementing http.Handler) with Action() and Shutdown(ctx) for draining detached durable-streaming runs after http.Server.Shutdown.

AgentRoutes returns the turn route plus the companion routes the agent supports (/getSnapshot, /waitForSnapshot, /abort) as []Route, each carrying a Kind (RouteKindTurn, RouteKindGetSnapshot, RouteKindWaitForSnapshot, RouteKindAbort) and a *genkithttp.Handler. Pattern() gives "POST /path" for ServeMux and Chi; Gin and Echo read Method and Path. It takes an interface rather than *aix.Agent[S], so one loop mounts agents with different state types. Filter by rt.Kind to leave a companion route out.

Middleware and the action context replace ContextProvider

func requireAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := verifyBearerToken(r.Context(), r.Header.Get("Authorization"))
		if err != nil {
			genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "sign in required"))
			return
		}
		next.ServeHTTP(w, r.WithContext(core.WithActionContextValue(r.Context(), "auth", user)))
	})
}

// In a flow or tool:
user, ok := core.ActionContextValue[User](ctx, "auth")

The action context stays the one place request values live, as in JS: middleware adds to it, the Dev UI and CLI --context fill it with JSON, flows read core.ActionContextValue[T](ctx, name), and templates read {{@name}}. WithActionContextValue copies the map, so chained middleware never overwrites or aliases a parent's values. ActionContextValue converts a Dev UI JSON object to a struct and a JSON number to an int. Prompt rendering caches the JSON form of struct values once per immutable context snapshot so Go's Handlebars engine resolves fields by JSON name ({{@auth.uid}}), and requests that render no template pay zero conversion cost.

firebase.AuthMiddleware, firebase.NewAuthMiddleware, and firebase.AuthFromContext replace firebase.ContextProvider. AuthMiddleware exposes both standard token fields and custom claims ({{@auth.email}}, etc.) to Dotprompt templates matching Dev UI runs, sets WWW-Authenticate: Bearer on 401 responses, and logs public 4xx rejections at DEBUG. Values only Go code reads use plain context.WithValue.

Durable streaming stays experimental

h := genkithttp.NewHandler(countdown,
	genkithttpx.WithStreamManager(corex.NewInMemoryStreamManager(corex.WithStreamTTL(10*time.Minute))),
)
mux.Handle("POST /countdown", h)
// During server shutdown:
_ = h.Shutdown(shutdownCtx)

WithStreamManager, WithStreamTimeout, HeaderStreamID, and HeaderLastEventID live in genkithttp/exp because StreamManager comes from core/exp (corex); the stable genkithttp package exposes no experimental types or headers.

  • Action-scoped streams and reconnect validation: stream storage keys are scoped per action so a shared StreamManager cannot cross-replay another action's stream. Sending X-Genkit-Stream-Id to a handler with no StreamManager returns HTTP 501 UNIMPLEMENTED instead of re-running the action; sending it on a non-streaming request returns 400.
  • Cursor resume: durable chunks emit 1-based SSE id: lines (StreamEvent.Index); reconnecting clients can send Last-Event-ID to skip already-received chunks (400 on invalid values). InMemoryStreamManager.Subscribe sizes its replay buffer to hold all buffered chunks plus the terminal event, avoiding deadlocks above 100 chunks, and Close() is idempotent.
  • Disconnect timeout, async persistence, and shutdown: WithStreamTimeout (default 10m) starts only when the client disconnects, so connected clients are not cut off. Chunks persist asynchronously in FIFO order (logging storage errors at WARN) and drain before recording Done/Error on a fresh 10s deadline. Panics on the detached goroutine become ErrPanic, WithOnError is called once, and Handler.Shutdown(ctx) waits for active detached runs to finish.

Wire protocol fixes

  • Strict request decoding: any non-empty body is read including chunked and HTTP/2 requests (ContentLength == -1), capped at 10 MiB by default (WithMaxBodyBytes, 413 past it). Non-empty POST bodies require Content-Type: application/json (415 otherwise); malformed JSON, unknown top-level envelope fields, and trailing JSON tokens get 400. Non-POST gets 405 with Allow: POST.
  • Stream negotiation: an explicit ?stream=<bool> decides (400 when invalid); otherwise Accept: text/event-stream asks for a stream unless q=0.
  • HTTP/2-safe SSE with deferred commit and configurable heartbeats: no Connection or Transfer-Encoding headers (RFC 9113), flushing through wrapped ResponseWriters via http.ResponseController, and keepalives every 15s (WithHeartbeat, 0 disables). SSE headers commit on the first chunk, heartbeat, or final result, so pre-stream schema, auth, and unknown-snapshot failures return real HTTP 4xx JSON responses instead of 200 OK SSE frames. The JS streamFlow client parser ignores SSE comments (: keepalive) and metadata lines (id:, event:, retry:) and exits cleanly on stream EOF.
  • Distributed tracing: X-Genkit-Trace-Id and X-Genkit-Span-Id are set on unary and SSE responses, incoming W3C traceparent/tracestate headers are extracted when no outer middleware has extracted a span context, and DefaultAllowedHeaders includes traceparent and tracestate.
  • Errors and details: pre-stream failures get a Genkit JSON error body with an HTTP status; mid-stream failures get an SSE error frame. status.Error.Details are preserved on public errors (and in GENKIT_ENV=dev) and redacted along with internal messages on non-public production errors. WithOnError receives the original error and request in both cases. Public 4xx errors log at DEBUG; all other errors log at ERROR.

API surface

// Added: package genkithttp
const HeaderTraceID, HeaderSpanID
DefaultAllowedHeaders() []string
DefaultExposedHeaders() []string
type Handler struct{ ... }
NewHandler(a api.Action, opts ...HandlerOption) *Handler
(*Handler).ServeHTTP(w http.ResponseWriter, r *http.Request)
(*Handler).Action() api.Action
(*Handler).Shutdown(ctx context.Context) error
type HandlerOption
WithMaxBodyBytes(n int64) HandlerOption
WithHeartbeat(d time.Duration) HandlerOption
WithOnError(fn func(r *http.Request, err error)) HandlerOption
WriteError(w http.ResponseWriter, err error)

// Added: package genkithttpx (genkithttp/exp)
const HeaderStreamID, HeaderLastEventID
type Agent interface { api.Action; GetSnapshotAction() api.Action; WaitForSnapshotAction() api.Action; AbortAction() api.Action }
type RouteKind string
const RouteKindTurn, RouteKindGetSnapshot, RouteKindWaitForSnapshot, RouteKindAbort RouteKind
type Route struct { Kind RouteKind; Method, Path string; Handler *genkithttp.Handler }
(Route).Pattern() string
AgentRoutes(path string, a Agent, opts ...genkithttp.HandlerOption) []Route
WithStreamManager(sm corex.StreamManager) genkithttp.HandlerOption
WithStreamTimeout(d time.Duration) genkithttp.HandlerOption

// Added: package core
WithActionContextValue(ctx context.Context, name string, value any) context.Context
ActionContextValue[T any](ctx context.Context, name string) (T, bool)

// Changed: package corex (core/exp)
StreamEvent.Index int

// Changed: plugins/firebase
firebase.AuthFromContext(ctx context.Context) (AuthContext, bool)
firebase.AuthPolicy = func(r *http.Request, token AuthContext) error
firebase.NewAuthMiddleware(client AuthClient, policy AuthPolicy) func(http.Handler) http.Handler
firebase.AuthMiddleware(ctx context.Context, g *genkit.Genkit, policy AuthPolicy) (func(http.Handler) http.Handler, error)

// Deleted
genkit.Handler, genkit.HandlerFunc, genkit.HandlerOption, genkit.WithContextProviders
genkitx.WithStreamManager
core.ContextProvider, core.RequestData
core.FromContext, core.WithActionContext, core.ActionContext
genkitx.Route, genkitx.AgentRoutes, genkitx.AllAgentRoutes, genkitx.FlowRoutes, genkitx.AllFlowRoutes
firebase.ContextProvider
plugins/server (module)

What is deliberately left out

Each of these can be added in a minor release; none can be removed after v2 ships.

  • No router. Go 1.22 ServeMux already matches method and exact path, and http.StripPrefix covers base paths.
  • No CORS middleware. Every router has one, as does github.com/rs/cors; DefaultAllowedHeaders and DefaultExposedHeaders configure them for the Genkit and W3C trace headers.
  • No ListenAndServe helper. Graceful shutdown of long SSE streams depends on the deploy target; http.Server and Handler.Shutdown leave that to the application. genkit.Init catches no signals, so a plain http.ListenAndServe ends on Ctrl+C.
  • No custom error encoder. Genkit clients, remote agents included, parse only the Genkit error shape.
  • No exported wire helpers (request decoding, SSE writer, stream negotiation). Custom transports can get them when needed.
  • No whole-map reader. One that returns the stored map lets a flow mutate its caller's values. ActionContextValue[any] returns one value as stored.
  • No typed context key. ActionContextValue[T] with a name constant covers what a key type would, and plain context.WithValue covers values only Go reads.
  • No AllAgentRoutes or AllFlowRoutes. What to expose is the app's choice, and genkitx.ListAgents includes remote-agent proxies, which would serve as an open relay calling other services with the app's credentials.

@github-actions github-actions Bot added docs Improvements or additions to documentation go labels Dec 3, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request migrates HTTP serving from the core genkit package and the plugins/server plugin to the new framework-agnostic genkithttp and genkithttp/exp packages, introducing a new Mux, NewHandler, and ListenAndServe utility. It also adds typed ContextKeys for request-scoped context propagation. A security issue was identified in the new CORS middleware, where reflecting the Origin header when AllowCredentials is enabled with a wildcard origin configuration allows unauthorized credentialed cross-origin requests.

Comment thread go/genkithttp/cors.go Resolved

@genkit-bot genkit-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few comments

Details

Run d268058f-08c3-4e98-b020-47db9721100b · Cloud Run logs · Dashboard

Comment thread go/genkithttp/handler.go Resolved
Comment thread go/genkithttp/handler.go Resolved
Comment thread go/core/context.go Resolved
Comment thread go/genkithttp/mux.go Resolved
Comment thread go/genkithttp/cors.go Resolved
Comment thread go/genkithttp/wire.go Resolved
genkit.ContextKey is the only typed context key; core keeps ActionContext,
WithActionContext, and FromContext. ContextKey.WithValue also stores the
value's JSON form in the action context under the key's name, so a template
reads it as {{@name}} (for example {{@auth.uid}} behind
firebase.AuthMiddleware), as it did with context providers. NewContextKey
panics on an empty name, and ContextKey.Name is no longer exported.

firebase.AuthMiddleware logs each rejected request before it writes the
Genkit error body.
…router

genkithttp serves one action per handler and leaves routing, CORS, auth, and
server lifecycle to the application's router and middleware. Its exported
surface is NewHandler with WithMaxBodyBytes and WithOnError, WriteError for
middleware, the X-Genkit-* header names, and DefaultAllowedHeaders and
DefaultExposedHeaders for configuring a CORS library. The request decoder,
result and SSE writers, and stream negotiation are unexported. An explicit
?stream=<bool> decides streaming, and an Accept entry with q=0 does not ask
for a stream.

genkithttp/exp holds the experimental parts. AgentRoutes(path, agent) returns
an agent's turn route and the companion routes it supports as []Route, which
mounts on net/http, Chi, Gin, or Echo; it takes any value with the companion
action accessors. WithStreamManager and WithStreamTimeout enable durable
streaming for a NewHandler route, so the stable package does not depend on
core/x/streaming.

A detached durable run reports its failure through WithOnError once, with the
original request. Samples and tests mount handlers on http.ServeMux and serve
with http.ListenAndServe.
README, package docs, and MIGRATION.md show flows mounted with
genkithttp.NewHandler and agents with genkithttpx.AgentRoutes on a standard
router, durable streaming through genkithttpx.WithStreamManager, and CORS
through the router's middleware with the Genkit header lists.
…er a timeout

A durable run executes on its own goroutine, outside net/http's per-request
recovery, so a panic in the action ended the process. The handler now turns
it into an ErrPanic error that the client and WithOnError receive.

A run that hits WithStreamTimeout ends with its context done, and a store
that honors the context (such as the Firestore stream manager) then rejected
the terminal write, so reconnecting clients waited without an end. The end
is now recorded on a fresh 10-second deadline that keeps the request's
values, and a failure to record it is logged.
The action context is the one place request values live, as in JS: HTTP
middleware adds to it with core.WithActionContextValue, the Dev UI and CLI
--context fill it with JSON, flows read it with core.FromContext, and
Dotprompt templates read it as {{@name}}. WithActionContextValue copies the
map, so middleware can each add a value without changing the parent context.

Prompt rendering gives templates the JSON form of a struct value, so
{{@auth.uid}} reads a field by its JSON name. Requests that render no
template do no conversion.

firebase.AuthFromContext replaces firebase.AuthKey. It returns the verified
token on a served request and decodes a Dev UI auth object the way the Admin
SDK decodes a token, with custom claims in Token.Claims.

Values that only Go code reads use plain context.WithValue.
The handler takes its stream manager from core/exp (corex), where durable
streaming lives, and genkithttpx.WithStreamManager is the one way to enable
it. genkitx.WithStreamManager configured genkit.Handler, which genkithttp
replaces, so it is removed along with its genkitbridge hook.

genkithttp/exp is package genkithttpx, the name it is imported as, like the
other experimental packages.
A failed reconnect went back to the top of the session loop, which started
register and readLoop on the closed connection, so each failed attempt spawned
a goroutine and logged errors. The session now waits in a backoff loop until a
dial succeeds.

The backoff shifted reconnectBaseDelay by the unbounded attempt count, which
overflows into a negative delay at attempt 35, about three minutes into a CLI
outage, after which retries did not wait. reconnectDelay stops the shift at
the cap.
Every failed request logged at ERROR, so malformed JSON, a wrong method, or a
lookup of an unknown snapshot each produced an error log line in production.
A public 4xx error, one made with status.PublicErrorf, is a deliberate
rejection of the request and now logs at DEBUG. Every other error stays at
ERROR, including 4xx errors that are not public: a model provider reports a
revoked server API key as UNAUTHENTICATED and a quota limit as
RESOURCE_EXHAUSTED, and those are the server's problem. WithOnError still
receives every error.
… reader

core.FromContext is core.ActionContextFromContext. The old name did not say
which context it returns, and genkit.FromContext returns a *Genkit.

core.ActionContextValue[T] reads one action context value as a T. HTTP
middleware stores Go values, but the Dev UI and CLI --context store decoded
JSON, so a value that is not already a T is converted through JSON. Flows no
longer need a type switch with a JSON fallback for each value they read.
core.ActionContextFromContext, core.WithActionContext, and the
core.ActionContext type are removed. Middleware adds a value with
core.WithActionContextValue and flows read one with
core.ActionContextValue[T]; ActionContextValue[any] returns a value as
stored. The removed reader returned the stored map, so a flow that wrote to
it changed the values its caller's context held.

The map lives in internal/actionctx for the code that fills or lists it: the
reflection servers and prompt rendering.
…nterop

Refines the Genkit Go v2 HTTP serving API before release so lifecycle
hooks, error wire fidelity, distributed tracing, request validation, and
durable streaming semantics are sound from v2.0.

- Return concrete *genkithttp.Handler from NewHandler with Action() and
  Shutdown(ctx), and export WithHeartbeat.
- Defer SSE header commit until first chunk, heartbeat, or result so
  pre-stream validation, auth, and snapshot errors return HTTP 4xx.
- Preserve status.Error.Details on public and dev wire errors; redact
  them on non-public production errors; handle WriteError(w, nil).
- Require Content-Type: application/json for non-empty POST bodies (415)
  and reject unknown envelope fields and trailing JSON tokens (400).
- Extract W3C traceparent/tracestate in NewHandler and include them in
  DefaultAllowedHeaders.
- Move HeaderStreamID out of stable genkithttp into genkithttp/exp
  alongside HeaderLastEventID; add RouteKind and concrete *Handler on
  genkithttpx.Route.
- Upgrade durable streaming: scope stream keys per action, reject
  X-Genkit-Stream-Id with 501 when disabled, start WithStreamTimeout
  only on disconnect, support Last-Event-ID chunk resume, persist chunks
  asynchronously with warning logs, fix InMemoryStreamManager >100-chunk
  subscribe deadlock, and drain detached runs in Handler.Shutdown.
- Update firebase.AuthMiddleware: export NewAuthMiddleware, simplify
  AuthPolicy, expose custom claims to Dotprompt, log public 4xx at
  debug, and send WWW-Authenticate: Bearer on 401.
- Cache Dotprompt action context template conversions per snapshot.
- Fix JS streamFlow SSE parsing to ignore comments and non-data lines.
- Fix researcher sample shutdown on stdin EOF and update docs/samples.
@github-actions github-actions Bot added the js label Dec 5, 2026
@apascal07
apascal07 merged commit d444dd2 into ap/go-v2 Dec 5, 2026
18 checks passed
@apascal07
apascal07 deleted the ap/go-v2-http-api branch December 5, 2026 19:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation go js

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants