From b908ea967ed82d1c5d2091164945d9cc4a7e3299 Mon Sep 17 00:00:00 2001 From: Alex Pascal Date: Thu, 3 Dec 2026 00:36:56 +0000 Subject: [PATCH] feat(go)!: redesign HTTP serving API with genkithttp and genkithttp/exp --- go/MIGRATION.md | 76 +- go/README.md | 16 +- go/ai/exp/agent.go | 25 +- go/ai/exp/handle.go | 4 +- go/ai/exp/remote.go | 10 +- go/context.go | 30 + go/core/context.go | 90 +- go/core/context_test.go | 105 ++ go/doc.go | 18 +- go/example_test.go | 13 +- go/exp/agent.go | 26 +- go/exp/agent_test.go | 20 +- go/exp/doc.go | 11 +- go/exp/route.go | 172 --- go/exp/route_test.go | 231 ---- go/genkithttp/cors.go | 125 ++ go/genkithttp/cors_server_test.go | 235 ++++ go/genkithttp/doc.go | 73 ++ go/genkithttp/example_test.go | 55 + go/genkithttp/exp/agent.go | 169 +++ go/genkithttp/exp/agent_test.go | 480 ++++++++ go/genkithttp/exp/doc.go | 35 + go/genkithttp/handler.go | 395 +++++++ go/genkithttp/handler_test.go | 1006 +++++++++++++++++ go/genkithttp/mux.go | 171 +++ go/genkithttp/mux_test.go | 214 ++++ go/genkithttp/option.go | 287 +++++ go/genkithttp/server.go | 117 ++ go/genkithttp/wire.go | 395 +++++++ go/go.work | 1 - go/internal/wire/wire.go | 33 +- go/middleware/exp/agents_async_test.go | 8 +- go/middleware/exp/helpers_test.go | 19 +- go/plugins/firebase/auth.go | 84 +- go/plugins/firebase/auth_test.go | 141 +++ go/plugins/server/go.mod | 3 - go/plugins/server/server.go | 74 -- go/reflection.go | 36 +- go/reflection_v2.go | 2 +- go/samples/anthropic/main.go | 9 +- go/samples/basic-agents-remote/main.go | 17 +- .../basic-agents-remote/researcher/main.go | 14 +- go/samples/basic-agents-server/main.go | 26 +- go/samples/basic-decisions/main.go | 9 +- .../basic-durable-streaming-exp/main.go | 13 +- go/samples/basic-errors/main.go | 9 +- go/samples/basic-flows/main.go | 9 +- go/samples/basic-formats/main.go | 9 +- go/samples/basic-media/main.go | 9 +- go/samples/basic-middleware/a2ui/main.go | 43 +- go/samples/basic-middleware/budget/main.go | 9 +- .../context-compression/main.go | 9 +- .../basic-middleware/filesystem/main.go | 9 +- go/samples/basic-middleware/metering/main.go | 9 +- .../basic-middleware/retry-fallback/main.go | 9 +- go/samples/basic-middleware/skills/main.go | 9 +- go/samples/basic-prompt-content/main.go | 9 +- go/samples/basic-prompts/main.go | 9 +- go/samples/basic-structured/main.go | 9 +- go/samples/basic-tool-interrupts/main.go | 9 +- go/samples/basic-tools/main.go | 9 +- go/samples/basic/main.go | 9 +- go/samples/compat_oai/anthropic/main.go | 9 +- go/samples/compat_oai/custom/main.go | 9 +- go/samples/compat_oai/dashscope/main.go | 9 +- go/samples/compat_oai/deepseek/main.go | 9 +- go/samples/compat_oai/kimi/main.go | 9 +- go/samples/compat_oai/mistral/main.go | 9 +- go/samples/compat_oai/openai/main.go | 9 +- go/samples/compat_oai/openrouter/main.go | 9 +- go/samples/compat_oai/xai/main.go | 9 +- go/samples/compat_oai/zai/main.go | 9 +- .../durable-streaming-firestore/main.go | 9 +- go/samples/go.mod | 3 - .../kitchen_sink/kitchen_sink.go | 9 +- .../telemetry-test/simple/simple_joke.go | 9 +- go/server.go | 537 --------- go/server_test.go | 854 -------------- go/servers_agent_test.go | 547 --------- go/servers_leak_test.go | 161 --- go/tests/test_app/main.go | 5 +- 81 files changed, 4529 insertions(+), 2975 deletions(-) create mode 100644 go/context.go delete mode 100644 go/exp/route.go delete mode 100644 go/exp/route_test.go create mode 100644 go/genkithttp/cors.go create mode 100644 go/genkithttp/cors_server_test.go create mode 100644 go/genkithttp/doc.go create mode 100644 go/genkithttp/example_test.go create mode 100644 go/genkithttp/exp/agent.go create mode 100644 go/genkithttp/exp/agent_test.go create mode 100644 go/genkithttp/exp/doc.go create mode 100644 go/genkithttp/handler.go create mode 100644 go/genkithttp/handler_test.go create mode 100644 go/genkithttp/mux.go create mode 100644 go/genkithttp/mux_test.go create mode 100644 go/genkithttp/option.go create mode 100644 go/genkithttp/server.go create mode 100644 go/genkithttp/wire.go create mode 100644 go/plugins/firebase/auth_test.go delete mode 100644 go/plugins/server/go.mod delete mode 100644 go/plugins/server/server.go delete mode 100644 go/server.go delete mode 100644 go/server_test.go delete mode 100644 go/servers_agent_test.go delete mode 100644 go/servers_leak_test.go diff --git a/go/MIGRATION.md b/go/MIGRATION.md index 4417c35c7e..c71c8ec1a3 100644 --- a/go/MIGRATION.md +++ b/go/MIGRATION.md @@ -889,14 +889,84 @@ A background model sets the error with `status.Errorf`: op.Error = status.Errorf(status.ErrUnavailable, "render failed: %s", msg) ``` +## HTTP serving moves to `genkithttp` and `genkithttp/exp` + +The HTTP action handlers, server helper, route builders, and custom context +providers are replaced by two framework-agnostic `net/http` packages: + +- `github.com/genkit-ai/genkit-go/v2/genkithttp` (`package genkithttp`) for + serving actions, routing (`Mux`, `HandleAction`), CORS middleware (`CORS`), + graceful standalone serving (`ListenAndServe`), and low-level wire helpers + (`WriteError`, `WriteResult`, `DecodeRequest`, `WantsStream`, `SSEWriter`). +- `github.com/genkit-ai/genkit-go/v2/genkithttp/exp` (`package exp`, commonly + aliased `genkithttpx`) for mounting experimental agents and their snapshot + companion routes (`HandleAgent`). + +| v1 / earlier v2 | v2 (`genkithttp`) | +| --- | --- | +| `genkit.Handler(a, opts...)` | `genkithttp.NewHandler(a, opts...)` | +| `genkit.HandlerFunc(a, opts...)` | Removed; use `genkithttp.NewHandler` with `WithOnError` / `WithErrorEncoder` | +| `genkit.WithStreamManager(sm)` | `genkithttp.WithStreamManager(sm)` | +| `server.Start(ctx, addr, mux)` (`plugins/server`) | `genkithttp.ListenAndServe(ctx, addr, handler, opts...)` | +| `genkitx.AgentRoutes`, `AllAgentRoutes`, `FlowRoutes`, `AllFlowRoutes`, `Route` | `genkithttp.NewMux`, `genkithttp.HandleAction`, `genkithttpx.HandleAgent`, `(*genkithttp.Mux).Routes` | +| `genkit.WithContextProviders`, `core.ContextProvider`, `core.RequestData` | Standard `net/http` middleware setting values on `r.Context()` + `genkithttp.WriteError` + `genkit.NewContextKey[T]` | +| `firebase.ContextProvider(ctx, g, policy)` | `firebase.AuthMiddleware(ctx, g, policy)` + `firebase.AuthKey` | + +**Before:** + +```go +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:** + +```go +var userKey = genkit.NewContextKey[User]("auth") + +func requireAuth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, err := verifyToken(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(userKey.WithValue(r.Context(), user))) + }) +} + +api := genkithttp.NewMux() +genkithttp.HandleAction(api, storyFlow) +genkithttpx.HandleAgent(api, chatAgent) + +mux := http.NewServeMux() +mux.Handle("/api/", http.StripPrefix("/api", requireAuth(api))) + +handler := genkithttp.CORS(genkithttp.CORSOptions{ + AllowedOrigins: []string{"https://myapp.dev"}, +})(mux) +log.Fatal(genkithttp.ListenAndServe(ctx, "", handler)) +``` + +`genkit.NewContextKey[T](name)` reads typed values set by HTTP middleware via +`WithValue` with zero JSON overhead, and falls back to decoding `name` from +`core.FromContext(ctx)` when flows run through the Dev UI or CLI `--context`. +Plain Go `context.WithValue` continues to work natively. + ## Smaller changes - **`api.Registry` is sealed.** Only Genkit implements it, so Genkit can add a method to it in a minor release. A test that needs a registry calls `genkit.Init`. -- **`WithPlugins` and `WithContextProviders` accumulate.** A second option - adds to the first instead of making `genkit.Init` return an error or - `genkit.Handler` panic, so a helper can extend a base option list. +- **`WithPlugins` accumulates.** A second `genkit.WithPlugins` option adds to + the first instead of making `genkit.Init` return an error, so a helper can + extend a base option list. - **A nil model or embedder sets nothing.** `ai.WithModel` and `ai.WithEmbedder` ignore the nil `*ai.Model`, `*ai.BackgroundModel`, or `*ai.Embedder` of a lookup that found nothing. It no longer replaces a model diff --git a/go/README.md b/go/README.md index cab3797eba..73c8034550 100644 --- a/go/README.md +++ b/go/README.md @@ -374,18 +374,16 @@ chatAgent := genkitx.DefineAgent(g, "chat", ### Serve Agents over HTTP -`AllAgentRoutes` serves every agent, one turn per request: +`genkithttpx.HandleAgent` mounts an agent and its companion routes on a `genkithttp.Mux`: ```go -mux := http.NewServeMux() -for _, r := range genkitx.AllAgentRoutes(g) { - mux.HandleFunc(r.Pattern(), r.Handler()) -} +api := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) +genkithttpx.HandleAgent(api, chatAgent) // POST /agents/chat one turn (?stream=true for SSE) // POST /agents/chat/getSnapshot read a snapshot // POST /agents/chat/waitForSnapshot wait for a snapshot to settle // POST /agents/chat/abort abort background work -if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { +if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", api); err != nil { log.Fatal(err) } ``` @@ -737,15 +735,15 @@ storyFlow := genkit.DefineStreamingFlow(g, "story", ) mux := http.NewServeMux() -mux.HandleFunc("POST /story", genkit.Handler(storyFlow)) -log.Fatal(http.ListenAndServe(":8080", mux)) +mux.Handle("POST /story", genkithttp.NewHandler(storyFlow)) +log.Fatal(genkithttp.ListenAndServe(ctx, ":8080", mux)) ``` ```bash curl -N "http://localhost:8080/story?stream=true" -d '{"data": "a robot who paints"}' ``` -`genkit.Handler` returns a standard `http.HandlerFunc`, so it works with Gin, Echo, Chi, or any router. [`genkit.WithStreamManager`](https://genkit.dev/docs/go/durable-streaming/) lets clients reconnect to a stream *(preview)*. +`genkithttp.NewHandler` and `genkithttp.Mux` implement `http.Handler`, so they work with `net/http`, Chi, Gin, Echo, or any router. [`genkithttp.WithStreamManager`](https://genkit.dev/docs/go/durable-streaming/) lets clients reconnect to a stream *(preview)*. [Docs](https://genkit.dev/docs/go/flows/) · [Example](samples/basic/main.go) · [Durable streaming example](samples/basic-durable-streaming-exp/main.go) diff --git a/go/ai/exp/agent.go b/go/ai/exp/agent.go index d717962449..d1e2e1eb3f 100644 --- a/go/ai/exp/agent.go +++ b/go/ai/exp/agent.go @@ -795,7 +795,8 @@ type AgentFunc[State any] = func(ctx context.Context, resp Responder, sess *Sess // Agent is a bidirectional streaming agent with automatic snapshot management. // // Agent implements [api.BidiAction], so generic transports accept it directly -// (e.g. pass it to genkit.Handler to serve it over HTTP, one turn per request). +// (e.g. mount it with genkithttpx.HandleAgent or genkithttp.NewHandler to serve +// it over HTTP, one turn per request). // [Agent.Run], [Agent.RunText], and [Agent.Connect] are typed conveniences // over the same underlying action. // @@ -836,9 +837,10 @@ func (a *Agent[State]) Name() string { // client-managed (no [SessionStore] configured): there is no server-side // snapshot to fetch. // -// Use it to expose snapshot polling over a transport (e.g. mount it with -// genkit.Handler next to the agent itself); local Go code should use -// [Agent.GetSnapshot], which applies the configured state transform. +// Use it to expose snapshot polling over a transport (e.g. via +// genkithttpx.HandleAgent or genkithttp.NewHandler next to the agent itself); +// local Go code should use [Agent.GetSnapshot], which applies the configured +// state transform. func (a *Agent[State]) GetSnapshotAction() api.Action { return a.getSnapshot } @@ -851,10 +853,11 @@ func (a *Agent[State]) GetSnapshotAction() api.Action { // until it settles. It returns nil when the agent is client-managed (no // [SessionStore] configured). // -// Use it to expose following a detached invocation over a transport (e.g. -// mount it with genkit.Handler next to the agent itself), so a remote caller -// waits in one request instead of a read per tick; local Go code should use -// [Agent.WaitForSnapshot], which applies the configured state transform. +// Use it to expose following a detached invocation over a transport (e.g. via +// genkithttpx.HandleAgent or genkithttp.NewHandler next to the agent itself), +// so a remote caller waits in one request instead of a read per tick; local Go +// code should use [Agent.WaitForSnapshot], which applies the configured state +// transform. func (a *Agent[State]) WaitForSnapshotAction() api.Action { return a.wait } @@ -865,8 +868,8 @@ func (a *Agent[State]) WaitForSnapshotAction() api.Action { // [AgentAbortResponse]). It returns nil when the agent has no // [SessionStore] or the store does not implement [SnapshotSubscriber]. // -// Use it to expose aborting over a transport (e.g. mount it with -// genkit.Handler next to the agent itself); local Go code aborts with +// Use it to expose aborting over a transport (e.g. via genkithttpx.HandleAgent +// or genkithttp.NewHandler next to the agent itself); local Go code aborts with // [Agent.Abort]; a store-only caller uses this companion action. func (a *Agent[State]) AbortAction() api.Action { return a.abort @@ -1256,7 +1259,7 @@ func newCustomAgent[State any]( ctx = cfg.contextFunc(ctx) } // A transport serving this agent to a client marks ctx (see - // genkit.Handler); the output it returns then keeps internal + // genkithttp.NewHandler); the output it returns then keeps internal // error text off the wire. served := wire.ServesAction(ctx, key) rt, err := newAgentRuntime(ctx, name, cfg, in, inCh, outCh) diff --git a/go/ai/exp/handle.go b/go/ai/exp/handle.go index cfef469c40..979bafea53 100644 --- a/go/ai/exp/handle.go +++ b/go/ai/exp/handle.go @@ -68,8 +68,8 @@ type AgentHandle struct { // refusal an agent that lacks a capability earns. Build a handle over one // with [NewAgentHandle]. // -// The methods mirror the agent's served routes (see the genkitx package's -// AgentRoutes) and take the wire types, so a field added to a request reaches +// The methods mirror the agent's served routes (see genkithttp/exp's +// HandleAgent) and take the wire types, so a field added to a request reaches // every transport without a new method. Snapshot operations live in the // optional [SnapshotTransport]. // diff --git a/go/ai/exp/remote.go b/go/ai/exp/remote.go index 53eb867a36..042e9f75d0 100644 --- a/go/ai/exp/remote.go +++ b/go/ai/exp/remote.go @@ -117,7 +117,7 @@ func WithAgentMetadata(meta *AgentMetadata) RemoteAgentOption { // --- NewRemoteAgent --- // NewRemoteAgent returns a handle to an agent that a Genkit app serves over -// HTTP, in Go (the genkitx package's AgentRoutes layout), JS, or Dart. url +// HTTP, in Go (via genkithttp/exp.HandleAgent), JS, or Dart. url // is the agent's turn route (e.g. "https://billing.internal/agents/billing"); // the snapshot companions are at url+"/getSnapshot", url+"/waitForSnapshot", // and url+"/abort", unless [WithRouteURLs] puts them elsewhere. It performs no @@ -228,7 +228,7 @@ const ( ) // httpTransport reaches an agent that a Genkit app serves over HTTP, through -// the routes of the genkitx package's AgentRoutes layout, speaking the +// the routes mounted by genkithttp/exp.HandleAgent, speaking the // wire format in internal/wire. type httpTransport struct { name string @@ -558,9 +558,9 @@ func olderGenkitError(mediaType string, body []byte) bool { // to the agent through the handle's transport. Such an agent action runs the // inputs of an invocation one after another, each as its own turn on the // transport, and carries the session from one turn to the next; a detach -// applies to the input that carries it. Serving layouts that list every agent -// (the genkitx package's AllAgentRoutes) skip it, so a server does not -// expose another service's agent with its own credentials. +// applies to the input that carries it. The descriptor carries +// [wire.RemoteAgentMetadataKey] so tooling can distinguish remote proxies from +// locally defined agents. // // Like every registration, it panics if r already holds an agent by the same // name. diff --git a/go/context.go b/go/context.go new file mode 100644 index 0000000000..e11d2a2d04 --- /dev/null +++ b/go/context.go @@ -0,0 +1,30 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkit + +import "github.com/genkit-ai/genkit-go/v2/core" + +// ContextKey is a typed key for storing and retrieving request-scoped values in +// a [context.Context], with fallback to Dev UI / CLI (--context) and Dotprompt +// [core.ActionContext] entries. +type ContextKey[T any] = core.ContextKey[T] + +// NewContextKey returns a new typed [ContextKey] associated with name for Dev +// UI (--context) and Dotprompt interoperability. +func NewContextKey[T any](name string) ContextKey[T] { + return core.NewContextKey[T](name) +} diff --git a/go/core/context.go b/go/core/context.go index 8e74908284..b8d44e45c7 100644 --- a/go/core/context.go +++ b/go/core/context.go @@ -39,17 +39,87 @@ func FromContext(ctx context.Context) ActionContext { return val.(ActionContext) } -// ActionContext is the runtime context for an Action. +// ActionContext is the runtime context for an Action, populated by the +// reflection server (Dev UI / CLI --context) and Dotprompt rendering. type ActionContext = map[string]any -// RequestData is the data associated with a request. -// It is used to provide additional context to the Action. -type RequestData struct { - Method string // Method is the HTTP method of the request (e.g. "GET", "POST", etc.) - Headers map[string]string // Headers is the headers of the request. The keys are the header names in lowercase. - Input json.RawMessage // Input is the body of the request. +// contextKeyToken is a unique unexported non-zero-sized allocation identifying +// a [ContextKey]. It must have non-zero size so Go allocates distinct addresses +// for every [NewContextKey] call rather than reusing runtime.zerobase. +type contextKeyToken struct { + _ byte } -// ContextProvider is a function that returns an ActionContext for a given request. -// It is used to provide additional context to the Action. -type ContextProvider = func(ctx context.Context, req RequestData) (ActionContext, error) +// contextKeyValue wraps a typed value stored in a [context.Context] so that a +// stored nil interface value is distinguishable from an absent key. +type contextKeyValue[T any] struct { + val T +} + +// ContextKey is a typed key for storing and retrieving request-scoped values in +// a [context.Context], with an automatic fallback to [FromContext] (the Dev UI / +// CLI --context map) for seamless local development and Dotprompt +// interoperability. +// +// Construct keys once at package level with [NewContextKey]. +type ContextKey[T any] struct { + name string + key *contextKeyToken +} + +// NewContextKey returns a unique typed [ContextKey] associated with name. +// When [ContextKey.FromContext] does not find a value stored via +// [ContextKey.WithValue] and name is non-empty, it falls back to looking up +// name in [FromContext] and JSON-unmarshaling the entry into T. +func NewContextKey[T any](name string) ContextKey[T] { + return ContextKey[T]{ + name: name, + key: new(contextKeyToken), + } +} + +// Name returns the fallback key name used for [ActionContext] lookups. +func (k ContextKey[T]) Name() string { + return k.name +} + +// WithValue attaches val to ctx under this typed key with zero JSON overhead. +// Panics if k was not constructed with [NewContextKey]. +func (k ContextKey[T]) WithValue(ctx context.Context, val T) context.Context { + if k.key == nil { + panic("core.ContextKey.WithValue: zero ContextKey; construct with NewContextKey") + } + return context.WithValue(ctx, k.key, contextKeyValue[T]{val: val}) +} + +// FromContext retrieves the typed value associated with k from ctx. +// +// Lookup order: +// 1. Fast path: a typed value stored via [ContextKey.WithValue]. +// 2. Dev/reflection fallback: if [FromContext] contains k.name, returns it +// directly when already of type T, or JSON-roundtrips it into T. +func (k ContextKey[T]) FromContext(ctx context.Context) (T, bool) { + if k.key != nil { + if v, ok := ctx.Value(k.key).(contextKeyValue[T]); ok { + return v.val, true + } + } + if k.name != "" { + if actionCtx := FromContext(ctx); actionCtx != nil { + if raw, exists := actionCtx[k.name]; exists { + if v, ok := raw.(T); ok { + return v, true + } + b, err := json.Marshal(raw) + if err == nil { + var v T + if err := json.Unmarshal(b, &v); err == nil { + return v, true + } + } + } + } + } + var zero T + return zero, false +} diff --git a/go/core/context_test.go b/go/core/context_test.go index 3ee4b8a0da..a3c9100781 100644 --- a/go/core/context_test.go +++ b/go/core/context_test.go @@ -120,3 +120,108 @@ func TestActionContextModification(t *testing.T) { } }) } + +func TestContextKey(t *testing.T) { + type authUser struct { + UID string `json:"uid"` + Admin bool `json:"admin"` + } + + userKey := NewContextKey[authUser]("auth") + otherKey := NewContextKey[authUser]("auth") + + t.Run("fast path round-trips typed value", func(t *testing.T) { + want := authUser{UID: "u-123", Admin: true} + ctx := userKey.WithValue(context.Background(), want) + + got, ok := userKey.FromContext(ctx) + if !ok { + t.Fatal("FromContext returned ok=false, want true") + } + if got != want { + t.Errorf("FromContext = %+v, want %+v", got, want) + } + + // A separate key with the same fallback name does not collide on the typed path. + if _, ok := otherKey.FromContext(ctx); ok { + t.Error("otherKey unexpectedly matched value stored under userKey") + } + }) + + t.Run("fallback decodes JSON map from ActionContext", func(t *testing.T) { + ctx := WithActionContext(context.Background(), ActionContext{ + "auth": map[string]any{ + "uid": "dev-456", + "admin": true, + }, + }) + + got, ok := userKey.FromContext(ctx) + if !ok { + t.Fatal("FromContext returned ok=false, want true") + } + want := authUser{UID: "dev-456", Admin: true} + if got != want { + t.Errorf("FromContext = %+v, want %+v", got, want) + } + }) + + t.Run("typed value takes precedence over ActionContext fallback", func(t *testing.T) { + ctx := WithActionContext(context.Background(), ActionContext{ + "auth": map[string]any{"uid": "from-action-ctx"}, + }) + ctx = userKey.WithValue(ctx, authUser{UID: "from-typed"}) + + got, ok := userKey.FromContext(ctx) + if !ok || got.UID != "from-typed" { + t.Errorf("FromContext = (%+v, %v), want UID=from-typed", got, ok) + } + }) + + t.Run("fallback returns direct value when already typed T", func(t *testing.T) { + want := authUser{UID: "direct"} + ctx := WithActionContext(context.Background(), ActionContext{"auth": want}) + + got, ok := userKey.FromContext(ctx) + if !ok || got != want { + t.Errorf("FromContext = (%+v, %v), want (%+v, true)", got, ok, want) + } + }) + + t.Run("missing key returns zero and false", func(t *testing.T) { + got, ok := userKey.FromContext(context.Background()) + if ok || got != (authUser{}) { + t.Errorf("FromContext = (%+v, %v), want (zero, false)", got, ok) + } + }) + + t.Run("incompatible fallback value returns zero and false", func(t *testing.T) { + ctx := WithActionContext(context.Background(), ActionContext{"auth": "not-an-object"}) + got, ok := userKey.FromContext(ctx) + if ok || got != (authUser{}) { + t.Errorf("FromContext = (%+v, %v), want (zero, false)", got, ok) + } + }) + + t.Run("zero ContextKey panics on WithValue and returns false on FromContext", func(t *testing.T) { + var zero ContextKey[string] + if _, ok := zero.FromContext(context.Background()); ok { + t.Error("zero.FromContext returned ok=true, want false") + } + defer func() { + if r := recover(); r == nil { + t.Error("zero.WithValue did not panic") + } + }() + zero.WithValue(context.Background(), "x") + }) + + t.Run("nil pointer value is distinguishable from absent", func(t *testing.T) { + ptrKey := NewContextKey[*authUser]("ptr") + ctx := ptrKey.WithValue(context.Background(), nil) + got, ok := ptrKey.FromContext(ctx) + if !ok || got != nil { + t.Errorf("FromContext = (%v, %v), want (nil, true)", got, ok) + } + }) +} diff --git a/go/doc.go b/go/doc.go index ebbc88cb6b..22e3b4017d 100644 --- a/go/doc.go +++ b/go/doc.go @@ -307,22 +307,24 @@ The Dev UI provides: # HTTP Server Integration -Expose flows as HTTP endpoints for production deployment using [Handler]: +Expose flows as HTTP endpoints for production deployment using package +[github.com/genkit-ai/genkit-go/v2/genkithttp]: - mux := http.NewServeMux() + api := genkithttp.NewMux() for _, flow := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+flow.Name(), genkit.Handler(flow)) + genkithttp.HandleAction(api, flow) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", api); err != nil { log.Fatal(err) } Handlers support streaming responses via Server-Sent Events when the client -sends Accept: text/event-stream. For durable streaming that survives reconnects, -use [WithStreamManager]: +sends Accept: text/event-stream or ?stream=true. For durable streaming that +survives reconnects, use [genkithttp.WithStreamManager]: - mux.HandleFunc("POST /countdown", genkit.Handler(countdown, - genkit.WithStreamManager(streaming.NewInMemoryStreamManager( + mux := http.NewServeMux() + mux.Handle("POST /countdown", genkithttp.NewHandler(countdown, + genkithttp.WithStreamManager(streaming.NewInMemoryStreamManager( streaming.WithTTL(10*time.Minute), )), )) diff --git a/go/example_test.go b/go/example_test.go index 58ef796324..9381ef422e 100644 --- a/go/example_test.go +++ b/go/example_test.go @@ -26,6 +26,7 @@ import ( genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // This example shows basic initialization and flow definition. @@ -230,21 +231,21 @@ func ExampleListFlows_httpServer() { }) // Create HTTP handlers for all flows - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, flow := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+flow.Name(), genkit.Handler(flow)) + genkithttp.HandleAction(mux, flow) } // The mux now has: // - POST /echo // - POST /reverse - fmt.Printf("Registered %d flow handlers\n", len(genkit.ListFlows(g))) + fmt.Printf("Registered %d flow handlers\n", len(mux.Routes())) // Output: Registered 2 flow handlers } -// This example demonstrates using Handler to expose a single flow +// This example demonstrates using genkithttp.NewHandler to expose a single flow // as an HTTP endpoint. -func ExampleHandler() { +func Example_httpHandler() { ctx := context.Background() g := genkit.MustInit(ctx) @@ -257,7 +258,7 @@ func ExampleHandler() { // Create an HTTP handler for the flow mux := http.NewServeMux() - mux.HandleFunc("POST /greet", genkit.Handler(greetFlow)) + mux.Handle("POST /greet", genkithttp.NewHandler(greetFlow)) // The handler accepts JSON: {"data": "World"} // and returns JSON: {"result": "Hello, World!"} diff --git a/go/exp/agent.go b/go/exp/agent.go index 2f69982f6c..3c13331798 100644 --- a/go/exp/agent.go +++ b/go/exp/agent.go @@ -47,11 +47,10 @@ import ( // (e.g. [aix.WithSessionStore], [aix.WithStateTransform]); pass an explicit // [State] only when no typed option is provided. // -// The returned agent is an [api.BidiAction]; pass it to [genkit.Handler] to -// serve it over HTTP, one turn per request. Server-managed agents also -// register companion actions for the snapshot lifecycle; serve them -// alongside the agent via [aix.Agent.GetSnapshotAction] and -// [aix.Agent.AbortAction]. +// The returned agent is an [api.BidiAction]; mount it on a +// [github.com/genkit-ai/genkit-go/v2/genkithttp.Mux] with +// [github.com/genkit-ai/genkit-go/v2/genkithttp/exp.HandleAgent] to serve it +// (and its snapshot companion actions) over HTTP, one turn per request. // // For full control over the per-turn loop, use [DefineCustomAgent]. // @@ -143,7 +142,9 @@ func DefinePromptAgent[State any]( // client sends the next message. // // Like [DefineAgent], the returned agent is an [api.BidiAction] servable -// via [genkit.Handler], with companion actions on [aix.Agent.GetSnapshotAction] +// via [github.com/genkit-ai/genkit-go/v2/genkithttp/exp.HandleAgent] (or +// [github.com/genkit-ai/genkit-go/v2/genkithttp.NewHandler]), with companion +// actions on [aix.Agent.GetSnapshotAction], [aix.Agent.WaitForSnapshotAction], // and [aix.Agent.AbortAction]. // // For agents backed by a prompt, use [DefineAgent] (inline prompt) or @@ -204,14 +205,13 @@ func DefineCustomAgent[State any]( // DefineRemoteAgent registers an agent that a Genkit app in Go, JS, or Dart // serves over HTTP and returns its [aix.AgentHandle]. It is // [aix.NewRemoteAgent] followed by [aix.AgentHandle.Register]: url is the -// agent's turn route in the [AgentRoutes] layout (e.g. -// "https://billing.internal/agents/billing"), and opts configure the HTTP -// client, headers, and route URLs and declare what the agent supports. +// agent's turn route (e.g. "https://billing.internal/agents/billing"), and opts +// configure the HTTP client, headers, and route URLs and declare what the agent +// supports. // // Once registered, the agent resolves by name like one defined in this // process: the agents middleware delegates to it with an [aix.AgentRef], and -// the Dev UI can call it. [AllAgentRoutes] does not serve it, so this app does -// not expose the other service's agent with its own credentials. +// the Dev UI can call it. // // Declare the agent's capabilities with [aix.WithAgentMetadata] and its // description with [aix.WithDescription]. Without metadata, callers treat its @@ -254,7 +254,9 @@ func LookupAgent(g *genkit.Genkit, name string) *aix.AgentHandle { // ListAgents returns a slice of all [api.Action] instances that represent // agents registered with the Genkit instance g. Like [genkit.ListFlows], this // is useful for introspection or for dynamically exposing agent endpoints in an -// HTTP server; an agent served via [genkit.Handler] runs one turn per request. +// HTTP server; an agent served via +// [github.com/genkit-ai/genkit-go/v2/genkithttp.NewHandler] runs one turn per +// request. func ListAgents(g *genkit.Genkit) []api.Action { reg := genkitbridge.RegistryOf(g) agents := []api.Action{} diff --git a/go/exp/agent_test.go b/go/exp/agent_test.go index 77064d5f17..db5fe297a1 100644 --- a/go/exp/agent_test.go +++ b/go/exp/agent_test.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "net/http" "net/http/httptest" "strings" "testing" @@ -32,6 +31,8 @@ import ( "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" "github.com/genkit-ai/genkit-go/v2/core/api" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" ) func TestLookupAgent(t *testing.T) { @@ -79,13 +80,12 @@ func TestLookupAgent(t *testing.T) { }) } -// serveAgents serves every agent registered with g over HTTP with the -// AllAgentRoutes layout and returns the server's base URL. -func serveAgents(t *testing.T, g *genkit.Genkit) string { +// serveAgents mounts agents under /agents and returns the test server's base URL. +func serveAgents[S any](t *testing.T, agents ...*aix.Agent[S]) string { t.Helper() - mux := http.NewServeMux() - for _, r := range AllAgentRoutes(g) { - mux.HandleFunc(r.Pattern(), r.Handler()) + mux := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) + for _, a := range agents { + genkithttpx.HandleAgent(mux, a) } srv := httptest.NewServer(mux) t.Cleanup(srv.Close) @@ -112,9 +112,9 @@ func TestDefineRemoteAgent(t *testing.T) { ctx := context.Background() server := genkit.MustInit(ctx, genkit.WithExperimental()) - DefineCustomAgent(server, "echo", countingEcho, + echoAgent := DefineCustomAgent(server, "echo", countingEcho, aix.WithSessionStore[any](localstore.NewInMemorySessionStore[any]())) - DefineCustomAgent(server, "broken", + brokenAgent := DefineCustomAgent(server, "broken", func(ctx context.Context, resp aix.Responder, sess *aix.SessionRunner[any]) (*aix.AgentResult, error) { err := sess.Run(ctx, func(ctx context.Context, input *aix.AgentInput) (*aix.TurnResult, error) { return nil, errors.New("dial 10.0.0.7:5432: password rejected") @@ -122,7 +122,7 @@ func TestDefineRemoteAgent(t *testing.T) { return nil, err }, aix.WithSessionStore[any](localstore.NewInMemorySessionStore[any]())) - base := serveAgents(t, server) + base := serveAgents(t, echoAgent, brokenAgent) client := genkit.MustInit(ctx, genkit.WithExperimental()) meta := &aix.AgentMetadata{StateManagement: aix.AgentStateManagementServer, Abortable: true} diff --git a/go/exp/doc.go b/go/exp/doc.go index 1d6e9c0c93..25b4a97df8 100644 --- a/go/exp/doc.go +++ b/go/exp/doc.go @@ -24,18 +24,11 @@ can churn without touching genkit's stable namespace. It currently provides: prompt sourced from the registry), and [DefineCustomAgent] (full control over the per-turn loop), plus [ListAgents] for introspection. An agent is a stateful, multi-turn conversational action built on bidirectional streaming; - serve one with [genkit.Handler] or the route builders below. + serve one over HTTP with + [github.com/genkit-ai/genkit-go/v2/genkithttp/exp.HandleAgent]. [DefineRemoteAgent] registers an agent that another Genkit app serves this way, so it resolves by name like one defined here. - - An HTTP route layout for serving agents and flows: the [Route] value and - the [AgentRoutes] / [AllAgentRoutes] / [FlowRoutes] / [AllFlowRoutes] - builders. Range over the routes and wire each onto an [http.ServeMux] (or - any router) with [Route.Pattern] and [Route.Handler]. The handlers - themselves come from the stable genkit package ([genkit.Handler]); this - package only lays out which paths map to which actions, so the routing - layer can evolve without touching genkit's stable surface. - - A channel-based streaming flow constructor, [DefineStreamingFlow]: an alternative to the callback-based [genkit.DefineStreamingFlow] for logic that is more naturally expressed by writing chunks to a channel. diff --git a/go/exp/route.go b/go/exp/route.go deleted file mode 100644 index 16a5a8ca58..0000000000 --- a/go/exp/route.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2026 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package exp - -import ( - "net/http" - - genkit "github.com/genkit-ai/genkit-go/v2" - aix "github.com/genkit-ai/genkit-go/v2/ai/exp" - "github.com/genkit-ai/genkit-go/v2/core/api" - "github.com/genkit-ai/genkit-go/v2/internal/wire" -) - -// Base paths for the built-in serving layouts. -const ( - agentBasePath = "/agents" - flowBasePath = "/flows" -) - -// Route is one HTTP route in a primitive's default serving layout: the -// method and path to mount and the action to serve. -// -// [AgentRoutes], [AllAgentRoutes], [FlowRoutes], and [AllFlowRoutes] -// produce Routes; range over them and wire each onto an [http.ServeMux] -// with [Route.Pattern] and [Route.Handler]. The fields are exported so -// other routers (Gin, Chi, Echo) can mount the same layout: read Method -// and Path and serve Action with [genkit.Handler]. -// Every route is a POST that speaks the {"data": ...} / {"result": ...} -// envelope of the reflection API (the agent turn route also streams via -// ?stream=true), so a single client transport reaches all of them. -type Route struct { - // Method is the HTTP method; always "POST" for the built-in layouts. - Method string - // Path is the URL path to mount, e.g. "/agents/chat/getSnapshot". - Path string - // Action is the action served at this route via [genkit.Handler]. - Action api.Action -} - -// Pattern returns the "METHOD /path" pattern for [http.ServeMux.HandleFunc]. -func (r Route) Pattern() string { - return r.Method + " " + r.Path -} - -// Handler builds the HTTP handler for this route with [genkit.Handler], -// applying opts. -func (r Route) Handler(opts ...genkit.HandlerOption) http.HandlerFunc { - return genkit.Handler(r.Action, opts...) -} - -// AllAgentRoutes returns the default serving layout for every agent -// registered with g, except remote agents ([DefineRemoteAgent]), the -// iterate-over-all counterpart to [AgentRoutes]. -// Mount the result onto an [http.ServeMux] (range over it and call -// [Route.Handler]) or hand it to a router of your choice. See -// [AgentRoutes] for the per-agent layout and the route set each agent -// contributes. -func AllAgentRoutes(g *genkit.Genkit) []Route { - var routes []Route - for _, act := range ListAgents(g) { - if act.Desc().Metadata[wire.RemoteAgentMetadataKey] == true { - // A remote agent (see DefineRemoteAgent) forwards to another - // service with this app's credentials; serving it here would - // hand those credentials to every caller of this app. - continue - } - name := act.Name() - // The snapshot-lifecycle companions register independently under - // their own action types, keyed by the agent's name (see the agent - // package's snapshot companions). Recover them by key so the layout - // depends only on the registry, not on the concrete agent type. - // LookupAction returns nil for a capability the agent lacks (a - // client-managed agent has no companions), and buildAgentRoutes omits - // the route for a nil companion. - snapshot := genkit.LookupAction(g, api.KeyFromName(api.ActionTypeAgentSnapshot, name)) - wait := genkit.LookupAction(g, api.KeyFromName(api.ActionTypeAgentWait, name)) - abort := genkit.LookupAction(g, api.KeyFromName(api.ActionTypeAgentAbort, name)) - routes = append(routes, buildAgentRoutes(name, act, snapshot, wait, abort)...) - } - return routes -} - -// AgentRoutes returns the default serving layout for a single agent, so you -// can mount specific agents rather than every registered one. Mount the -// result onto an [http.ServeMux], or onto a router of your choice. -// -// The route set mirrors what the agent can do: -// -// - POST /agents/{name} the agent, one turn per request -// - POST /agents/{name}/getSnapshot getSnapshot (store-backed agents) -// - POST /agents/{name}/waitForSnapshot waitForSnapshot (store-backed -// agents); getSnapshot's blocking counterpart, so a client follows a -// detached invocation without polling. One request holds for at most -// the agent's wait limit (see aix.WithMaxSnapshotWait) and then returns -// the snapshot as it stands; a client whose snapshot is still pending -// or aborting asks again -// - POST /agents/{name}/abort abort (abortable stores) -// -// Each takes the {"data": ...} request envelope and returns {"result": -// ...}; the snapshot ID rides in the body ({"data": {"snapshotId": ...}}), -// the same as the reflection API. Companion routes are omitted for -// capabilities the agent lacks; a client-managed agent contributes only -// its turn route. -// -// Each route serves through [genkit.Handler], so the errors in the agent's -// outputs and snapshots reach clients under its error policy. -func AgentRoutes[State any](a *aix.Agent[State]) []Route { - return buildAgentRoutes(a.Name(), a, a.GetSnapshotAction(), a.WaitForSnapshotAction(), a.AbortAction()) -} - -// buildAgentRoutes builds an agent's route set from its run action and the -// companion actions it has (any may be nil). Shared by AllAgentRoutes -// (companions looked up by key) and AgentRoutes (companions from the typed -// ref's accessors). -func buildAgentRoutes(name string, run, snapshot, wait, abort api.Action) []Route { - routes := []Route{{Method: http.MethodPost, Path: agentBasePath + "/" + name, Action: run}} - for _, companion := range []struct { - suffix string - action api.Action - }{ - {"/getSnapshot", snapshot}, - {"/waitForSnapshot", wait}, - {"/abort", abort}, - } { - if companion.action == nil { - continue - } - routes = append(routes, Route{ - Method: http.MethodPost, - Path: agentBasePath + "/" + name + companion.suffix, - Action: companion.action, - }) - } - return routes -} - -// AllFlowRoutes returns the default serving layout for every flow -// registered with g, the iterate-over-all counterpart to [FlowRoutes]. -// Mount the result onto an [http.ServeMux], or onto a router of your choice. -func AllFlowRoutes(g *genkit.Genkit) []Route { - var routes []Route - for _, f := range genkit.ListFlows(g) { - routes = append(routes, buildFlowRoute(f)) - } - return routes -} - -// FlowRoutes returns the default serving layout for a single flow: one -// route, POST /flows/{name}, taking its input from the request body. It -// returns a slice for symmetry with [AgentRoutes], so route lists compose -// with append. -func FlowRoutes(f api.Action) []Route { - return []Route{buildFlowRoute(f)} -} - -func buildFlowRoute(f api.Action) Route { - return Route{Method: http.MethodPost, Path: flowBasePath + "/" + f.Name(), Action: f} -} diff --git a/go/exp/route_test.go b/go/exp/route_test.go deleted file mode 100644 index 04e6510691..0000000000 --- a/go/exp/route_test.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2026 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package exp - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "slices" - "strings" - "testing" - - genkit "github.com/genkit-ai/genkit-go/v2" - "github.com/genkit-ai/genkit-go/v2/ai" - aix "github.com/genkit-ai/genkit-go/v2/ai/exp" - "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" -) - -// routeKey is a compact "METHOD path" identity for asserting on a route set -// without depending on order. -func routeKey(r Route) string { return r.Method + " " + r.Path } - -func routeKeys(routes []Route) []string { - keys := make([]string, len(routes)) - for i, r := range routes { - keys[i] = routeKey(r) - } - slices.Sort(keys) - return keys -} - -// newRouteTestGenkit defines a server-managed agent (with abortable store), -// a client-managed agent, and a flow, the mix the route builders must -// distinguish. -func newRouteTestGenkit(t *testing.T) *genkit.Genkit { - t.Helper() - g := genkit.MustInit(context.Background(), genkit.WithExperimental()) - - genkit.DefineModel(g, "test/echo", &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true}}, - func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { - return &ai.ModelResponse{ - Message: ai.NewModelTextMessage(fmt.Sprintf("echo %d", len(req.Messages))), - FinishReason: ai.FinishReasonStop, - }, nil - }) - - store, err := localstore.NewFileSessionStore[any](t.TempDir()) - if err != nil { - t.Fatal(err) - } - DefineAgent(g, "serverChat", aix.InlinePrompt{ai.WithModelName("test/echo")}, - aix.WithSessionStore(store), - ) - DefineAgent[any](g, "clientChat", aix.InlinePrompt{ai.WithModelName("test/echo")}) - genkit.DefineFlow(g, "greet", func(ctx context.Context, name string) (string, error) { - return "hi " + name, nil - }) - - return g -} - -func TestAllAgentRoutes(t *testing.T) { - g := newRouteTestGenkit(t) - // A remote agent forwards with this app's credentials, so the layout - // must not serve it: it is absent from the want list below. - DefineRemoteAgent(g, "billing", "https://billing.internal/agents/billing") - - got := routeKeys(AllAgentRoutes(g)) - want := []string{ - "POST /agents/clientChat", - "POST /agents/serverChat", - "POST /agents/serverChat/abort", - "POST /agents/serverChat/getSnapshot", - "POST /agents/serverChat/waitForSnapshot", - } - if !slices.Equal(got, want) { - t.Errorf("AllAgentRoutes layout =\n %v\nwant\n %v", got, want) - } - - // Every route is a POST carrying a non-nil action; companions are plain - // subpaths served with the same enveloped Handler as the turn route. - for _, r := range AllAgentRoutes(g) { - if r.Action == nil { - t.Errorf("route %q has nil Action", routeKey(r)) - } - if r.Method != http.MethodPost { - t.Errorf("route %q method = %q, want POST", routeKey(r), r.Method) - } - } -} - -func TestAgentRoutes_PicksOneAgentAndMirrorsCapabilities(t *testing.T) { - g := genkit.MustInit(context.Background(), genkit.WithExperimental()) - genkit.DefineModel(g, "test/echo", &ai.ModelOptions{}, - func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { - return &ai.ModelResponse{Message: ai.NewModelTextMessage("ok"), FinishReason: ai.FinishReasonStop}, nil - }) - store, err := localstore.NewFileSessionStore[any](t.TempDir()) - if err != nil { - t.Fatal(err) - } - server := DefineAgent(g, "srv", aix.InlinePrompt{ai.WithModelName("test/echo")}, aix.WithSessionStore(store)) - client := DefineAgent[any](g, "cli", aix.InlinePrompt{ai.WithModelName("test/echo")}) - - if got, want := routeKeys(AgentRoutes(server)), []string{ - "POST /agents/srv", - "POST /agents/srv/abort", - "POST /agents/srv/getSnapshot", - "POST /agents/srv/waitForSnapshot", - }; !slices.Equal(got, want) { - t.Errorf("AgentRoutes(server) = %v, want %v", got, want) - } - - // Client-managed: just the turn route, no companions. - if got, want := routeKeys(AgentRoutes(client)), []string{"POST /agents/cli"}; !slices.Equal(got, want) { - t.Errorf("AgentRoutes(client) = %v, want %v", got, want) - } -} - -func TestAllFlowRoutes(t *testing.T) { - g := newRouteTestGenkit(t) - - got := routeKeys(AllFlowRoutes(g)) - if want := []string{"POST /flows/greet"}; !slices.Equal(got, want) { - t.Errorf("AllFlowRoutes = %v, want %v", got, want) - } - - greet := genkit.NewFlow("standalone", func(ctx context.Context, s string) (string, error) { return s, nil }) - single := FlowRoutes(greet) - if len(single) != 1 || routeKey(single[0]) != "POST /flows/standalone" { - t.Errorf("FlowRoutes = %v, want one POST /flows/standalone", routeKeys(single)) - } -} - -// TestRoutesServedOverServeMux exercises the full path: build the all-agents -// layout, wire it onto a ServeMux, and drive the resulting endpoints. It -// proves every route speaks the same enveloped Handler transport (the turn -// and the getSnapshot companion alike) and that a client-managed agent has -// only its turn route. -func TestRoutesServedOverServeMux(t *testing.T) { - g := newRouteTestGenkit(t) - - mux := http.NewServeMux() - for _, route := range AllAgentRoutes(g) { - mux.HandleFunc(route.Pattern(), route.Handler()) - } - - do := func(t *testing.T, method, path, body string) (int, string) { - t.Helper() - var rdr io.Reader - if body != "" { - rdr = strings.NewReader(body) - } - req := httptest.NewRequest(method, path, rdr) - if body != "" { - req.Header.Set("Content-Type", "application/json") - } - w := httptest.NewRecorder() - mux.ServeHTTP(w, req) - b, _ := io.ReadAll(w.Result().Body) - return w.Result().StatusCode, string(b) - } - - // A turn on the server-managed agent goes through the enveloped Handler - // transport and yields a snapshot. - code, body := do(t, "POST", "/agents/serverChat", - `{"data":{"message":{"role":"user","content":[{"text":"hi"}]}}}`) - if code != http.StatusOK { - t.Fatalf("turn status = %d, body = %s", code, body) - } - var env struct { - Result struct { - SnapshotID string `json:"snapshotId"` - } `json:"result"` - } - if err := json.Unmarshal([]byte(body), &env); err != nil { - t.Fatalf("turn not enveloped as expected: %v; body = %s", err, body) - } - if env.Result.SnapshotID == "" { - t.Fatalf("no snapshotId from turn; body = %s", body) - } - - // The mounted getSnapshot route is a POST taking the snapshot ID in the - // {"data": ...} body and returning the snapshot in the {"result": ...} - // envelope, exactly like the turn route. - code, body = do(t, "POST", "/agents/serverChat/getSnapshot", - `{"data":{"snapshotId":"`+env.Result.SnapshotID+`"}}`) - if code != http.StatusOK { - t.Fatalf("getSnapshot status = %d, body = %s", code, body) - } - var snapEnv struct { - Result struct { - SnapshotID string `json:"snapshotId"` - } `json:"result"` - } - if err := json.Unmarshal([]byte(body), &snapEnv); err != nil { - t.Fatalf("getSnapshot not enveloped as expected: %v; body = %s", err, body) - } - if snapEnv.Result.SnapshotID != env.Result.SnapshotID { - t.Errorf("snapshot id = %q, want %q", snapEnv.Result.SnapshotID, env.Result.SnapshotID) - } - - // The client-managed agent is reachable... - code, body = do(t, "POST", "/agents/clientChat", - `{"data":{"message":{"role":"user","content":[{"text":"hi"}]}}}`) - if code != http.StatusOK { - t.Fatalf("client turn status = %d, body = %s", code, body) - } - // ...but has no companion route mounted. - code, _ = do(t, "POST", "/agents/clientChat/getSnapshot", `{"data":{"snapshotId":"whatever"}}`) - if code != http.StatusNotFound { - t.Errorf("client-managed agent should have no getSnapshot route; status = %d, want 404", code) - } -} diff --git a/go/genkithttp/cors.go b/go/genkithttp/cors.go new file mode 100644 index 0000000000..c95bad6c17 --- /dev/null +++ b/go/genkithttp/cors.go @@ -0,0 +1,125 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "net/http" + "slices" + "strconv" + "strings" + "time" +) + +// CORSOptions configures the [CORS] middleware. +type CORSOptions struct { + // AllowedOrigins lists permitted origins. Default: []string{"*"}. + AllowedOrigins []string + // AllowedMethods lists permitted HTTP methods. Default: []string{"POST", "OPTIONS"}. + AllowedMethods []string + // AllowedHeaders lists permitted request headers. Default: [DefaultAllowedHeaders]. + AllowedHeaders []string + // ExposedHeaders lists response headers exposed to browsers. Default: [DefaultExposedHeaders]. + ExposedHeaders []string + // AllowCredentials sets Access-Control-Allow-Credentials: true. + AllowCredentials bool + // MaxAge sets Access-Control-Max-Age on preflight responses when > 0. + MaxAge time.Duration +} + +// CORS returns standard [net/http] middleware applying CORS headers and +// answering OPTIONS preflight requests with 204 No Content. +// +// When specific origins are configured, a matching Origin is echoed back with +// "Vary: Origin"; non-matching origins receive no CORS headers. +func CORS(opts CORSOptions) func(http.Handler) http.Handler { + allowedOrigins := slices.Clone(opts.AllowedOrigins) + if len(allowedOrigins) == 0 { + allowedOrigins = []string{"*"} + } + allowAll := slices.Contains(allowedOrigins, "*") + + allowedMethods := slices.Clone(opts.AllowedMethods) + if len(allowedMethods) == 0 { + allowedMethods = []string{http.MethodPost, http.MethodOptions} + } + methodsHeader := strings.Join(allowedMethods, ", ") + + allowedHeaders := slices.Clone(opts.AllowedHeaders) + if len(allowedHeaders) == 0 { + allowedHeaders = DefaultAllowedHeaders() + } + headersHeader := strings.Join(allowedHeaders, ", ") + + exposedHeaders := slices.Clone(opts.ExposedHeaders) + if len(exposedHeaders) == 0 { + exposedHeaders = DefaultExposedHeaders() + } + exposedHeader := strings.Join(exposedHeaders, ", ") + + allowCredentials := opts.AllowCredentials + var maxAgeHeader string + if opts.MaxAge > 0 { + maxAgeHeader = strconv.Itoa(int(opts.MaxAge.Seconds())) + } + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + origin := r.Header.Get("Origin") + var allowOrigin string + var varyOrigin bool + + if allowAll { + if allowCredentials && origin != "" { + allowOrigin = origin + varyOrigin = true + } else { + allowOrigin = "*" + } + } else if origin != "" && slices.Contains(allowedOrigins, origin) { + allowOrigin = origin + varyOrigin = true + } + + if allowOrigin != "" { + w.Header().Set("Access-Control-Allow-Origin", allowOrigin) + if varyOrigin { + w.Header().Add("Vary", "Origin") + } + if allowCredentials { + w.Header().Set("Access-Control-Allow-Credentials", "true") + } + if exposedHeader != "" { + w.Header().Set("Access-Control-Expose-Headers", exposedHeader) + } + } + + if r.Method == http.MethodOptions { + if allowOrigin != "" { + w.Header().Set("Access-Control-Allow-Methods", methodsHeader) + w.Header().Set("Access-Control-Allow-Headers", headersHeader) + if maxAgeHeader != "" { + w.Header().Set("Access-Control-Max-Age", maxAgeHeader) + } + } + w.WriteHeader(http.StatusNoContent) + return + } + + next.ServeHTTP(w, r) + }) + } +} diff --git a/go/genkithttp/cors_server_test.go b/go/genkithttp/cors_server_test.go new file mode 100644 index 0000000000..39c28ee1f0 --- /dev/null +++ b/go/genkithttp/cors_server_test.go @@ -0,0 +1,235 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestDefaultHeaderSlicesAreFresh(t *testing.T) { + a := DefaultAllowedHeaders() + a[0] = "Mutated" + if got := DefaultAllowedHeaders()[0]; got == "Mutated" { + t.Error("DefaultAllowedHeaders returned shared slice") + } + + e := DefaultExposedHeaders() + e[0] = "Mutated" + if got := DefaultExposedHeaders()[0]; got == "Mutated" { + t.Error("DefaultExposedHeaders returned shared slice") + } +} + +func TestCORS(t *testing.T) { + okHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) + }) + + t.Run("wildcard defaults and OPTIONS preflight", func(t *testing.T) { + h := CORS(CORSOptions{MaxAge: 5 * time.Minute})(okHandler) + + req := httptest.NewRequest(http.MethodOptions, "/flow", nil) + req.Header.Set("Origin", "https://app.example") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusNoContent { + t.Errorf("OPTIONS status = %d, want 204", w.Code) + } + if got := w.Header().Get("Access-Control-Allow-Origin"); got != "*" { + t.Errorf("Allow-Origin = %q, want *", got) + } + if got := w.Header().Get("Access-Control-Allow-Methods"); got != "POST, OPTIONS" { + t.Errorf("Allow-Methods = %q, want POST, OPTIONS", got) + } + allowHeaders := w.Header().Get("Access-Control-Allow-Headers") + for _, want := range []string{"Content-Type", "Accept", "Authorization", HeaderStreamID} { + if !strings.Contains(allowHeaders, want) { + t.Errorf("Allow-Headers = %q, missing %q", allowHeaders, want) + } + } + exposeHeaders := w.Header().Get("Access-Control-Expose-Headers") + for _, want := range []string{HeaderTraceID, HeaderSpanID, HeaderStreamID} { + if !strings.Contains(exposeHeaders, want) { + t.Errorf("Expose-Headers = %q, missing %q", exposeHeaders, want) + } + } + if got := w.Header().Get("Access-Control-Max-Age"); got != "300" { + t.Errorf("Max-Age = %q, want 300", got) + } + }) + + t.Run("allowlist echoes matching origin with Vary and blocks others", func(t *testing.T) { + h := CORS(CORSOptions{ + AllowedOrigins: []string{"https://myapp.dev"}, + AllowCredentials: true, + })(okHandler) + + // Matching origin. + reqOK := httptest.NewRequest(http.MethodPost, "/flow", nil) + reqOK.Header.Set("Origin", "https://myapp.dev") + wOK := httptest.NewRecorder() + h.ServeHTTP(wOK, reqOK) + + if wOK.Code != http.StatusOK { + t.Errorf("status = %d, want 200", wOK.Code) + } + if got := wOK.Header().Get("Access-Control-Allow-Origin"); got != "https://myapp.dev" { + t.Errorf("Allow-Origin = %q, want https://myapp.dev", got) + } + if got := wOK.Header().Get("Vary"); !strings.Contains(got, "Origin") { + t.Errorf("Vary = %q, want Origin", got) + } + if got := wOK.Header().Get("Access-Control-Allow-Credentials"); got != "true" { + t.Errorf("Allow-Credentials = %q, want true", got) + } + + // Blocked origin receives NO CORS headers. + reqBad := httptest.NewRequest(http.MethodPost, "/flow", nil) + reqBad.Header.Set("Origin", "https://evil.example") + wBad := httptest.NewRecorder() + h.ServeHTTP(wBad, reqBad) + + for _, hdr := range []string{ + "Access-Control-Allow-Origin", + "Access-Control-Allow-Credentials", + "Access-Control-Expose-Headers", + } { + if got := wBad.Header().Get(hdr); got != "" { + t.Errorf("blocked origin received %s = %q, want empty", hdr, got) + } + } + + // Blocked origin preflight returns 204 with no CORS headers. + reqBadOpt := httptest.NewRequest(http.MethodOptions, "/flow", nil) + reqBadOpt.Header.Set("Origin", "https://evil.example") + wBadOpt := httptest.NewRecorder() + h.ServeHTTP(wBadOpt, reqBadOpt) + if wBadOpt.Code != http.StatusNoContent { + t.Errorf("blocked OPTIONS status = %d, want 204", wBadOpt.Code) + } + if got := wBadOpt.Header().Get("Access-Control-Allow-Origin"); got != "" { + t.Errorf("blocked OPTIONS received Allow-Origin = %q", got) + } + }) +} + +func TestListenAndServe(t *testing.T) { + t.Run("server defaults set ReadHeaderTimeout and leave WriteTimeout unset", func(t *testing.T) { + t.Setenv("PORT", "") + srv := newHTTPServer("", http.NewServeMux(), defaultServerConfig()) + if srv.Addr != "0.0.0.0:3400" { + t.Errorf("default Addr = %q, want 0.0.0.0:3400", srv.Addr) + } + if srv.ReadHeaderTimeout <= 0 { + t.Errorf("ReadHeaderTimeout = %v, want > 0", srv.ReadHeaderTimeout) + } + if srv.WriteTimeout != 0 { + t.Errorf("WriteTimeout = %v, want 0", srv.WriteTimeout) + } + + t.Setenv("PORT", "9090") + srv2 := newHTTPServer("", http.NewServeMux(), defaultServerConfig()) + if srv2.Addr != "0.0.0.0:9090" { + t.Errorf("PORT Addr = %q, want 0.0.0.0:9090", srv2.Addr) + } + }) + + t.Run("rejects nil handler and negative options", func(t *testing.T) { + if err := ListenAndServe(context.Background(), "127.0.0.1:0", nil); err == nil { + t.Error("expected error for nil handler") + } + if err := ListenAndServe(context.Background(), "127.0.0.1:0", http.NewServeMux(), WithShutdownTimeout(-time.Second)); err == nil { + t.Error("expected error for negative shutdown timeout") + } + if err := ListenAndServe(context.Background(), "127.0.0.1:0", http.NewServeMux(), WithReadHeaderTimeout(-time.Second)); err == nil { + t.Error("expected error for negative read header timeout") + } + }) + + t.Run("gracefully drains in-flight requests on context cancellation", func(t *testing.T) { + inFlight := make(chan struct{}) + release := make(chan struct{}) + h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(inFlight) + <-release + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("drained")) + }) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + + ctx, cancel := context.WithCancel(context.Background()) + srv := newHTTPServer(addr, h, defaultServerConfig()) + + srvErr := make(chan error, 1) + go func() { + srvErr <- serve(ctx, srv, ln, defaultServerConfig()) + }() + + respCh := make(chan *http.Response, 1) + reqErrCh := make(chan error, 1) + go func() { + resp, err := http.Get("http://" + addr + "/") + if err != nil { + reqErrCh <- err + return + } + respCh <- resp + }() + + <-inFlight + // Trigger graceful shutdown while request is still in-flight. + cancel() + + // Release handler slightly later; Shutdown should wait for it. + time.Sleep(30 * time.Millisecond) + close(release) + + select { + case err := <-reqErrCh: + t.Fatalf("in-flight HTTP request failed during drain: %v", err) + case resp := <-respCh: + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Errorf("in-flight status = %d, want 200", resp.StatusCode) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for in-flight request") + } + + select { + case err := <-srvErr: + if err != nil { + t.Errorf("serve returned error: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for server shutdown") + } + }) +} diff --git a/go/genkithttp/doc.go b/go/genkithttp/doc.go new file mode 100644 index 0000000000..29df35b9e2 --- /dev/null +++ b/go/genkithttp/doc.go @@ -0,0 +1,73 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +/* +Package genkithttp serves Genkit actions over HTTP using standard [net/http] +handlers, speaking the Genkit HTTP wire protocol (unary JSON and Server-Sent +Events streaming). + +Because every surface builds directly on [http.Handler], it works out of the +box with the standard library [http.ServeMux] as well as third-party routers +such as Chi, Gin, and Echo — with no framework-specific plugins required. + +# Serving Actions + +Mount a single action with [NewHandler]: + + mux := http.NewServeMux() + mux.Handle("POST /hello", genkithttp.NewHandler(helloFlow)) + +Mount multiple actions (and experimental agents via +[github.com/genkit-ai/genkit-go/v2/genkithttp/exp.HandleAgent]) on a [Mux]: + + api := genkithttp.NewMux() + genkithttp.HandleAction(api, storyFlow) + genkithttp.HandleAction(api, jokeFlow) + + mux := http.NewServeMux() + mux.Handle("/api/", http.StripPrefix("/api", requireAuth(api))) + + handler := genkithttp.CORS(genkithttp.CORSOptions{ + AllowedOrigins: []string{"https://myapp.dev"}, + })(mux) + log.Fatal(genkithttp.ListenAndServe(ctx, "", handler)) + +Use [Mux.Routes] when you prefer native per-route registration in a router +like Gin or Echo. + +# Authentication and Request Context + +Authentication and request-scoped values flow through standard HTTP middleware +into [http.Request.Context]. Use [WriteError] inside auth middleware to emit +wire-compatible Genkit JSON error responses, and [genkit.NewContextKey] when +you also want typed context values to read from Dev UI / CLI --context JSON. + +# Wire Protocol + +Every action endpoint accepts HTTP POST requests with a JSON body of the form +{"data": } (and optional "init" for bidirectional actions): + + - Unary requests return 200 OK with {"result": }. + - Streaming requests (triggered by ?stream=true or an Accept header + containing text/event-stream) return SSE frames: + data: {"message": }, followed by data: {"result": } or + data: {"error": {"status": "", "message": ""}}. + - Responses include X-Genkit-Trace-Id and X-Genkit-Span-Id headers on both + unary and streaming calls. + - Outside GENKIT_ENV=dev, internal error messages not constructed with + [status.PublicErrorf] are redacted to generic status labels. +*/ +package genkithttp diff --git a/go/genkithttp/example_test.go b/go/genkithttp/example_test.go new file mode 100644 index 0000000000..ac23696fe7 --- /dev/null +++ b/go/genkithttp/example_test.go @@ -0,0 +1,55 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp_test + +import ( + "context" + "fmt" + "net/http" + + genkit "github.com/genkit-ai/genkit-go/v2" + "github.com/genkit-ai/genkit-go/v2/genkithttp" +) + +func ExampleNewMux() { + g := genkit.MustInit(context.Background()) + + greetFlow := genkit.DefineFlow(g, "greet", func(ctx context.Context, name string) (string, error) { + return fmt.Sprintf("Hello, %s!", name), nil + }) + + api := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttp.HandleAction(api, greetFlow) + + for _, rt := range api.Routes() { + fmt.Println(rt.Pattern()) + } + // Output: POST /api/greet +} + +func ExampleNewHandler() { + g := genkit.MustInit(context.Background()) + + helloFlow := genkit.DefineFlow(g, "hello", func(ctx context.Context, name string) (string, error) { + return "Hello, " + name, nil + }) + + mux := http.NewServeMux() + mux.Handle("POST /hello", genkithttp.NewHandler(helloFlow)) + fmt.Println("Mounted POST /hello") + // Output: Mounted POST /hello +} diff --git a/go/genkithttp/exp/agent.go b/go/genkithttp/exp/agent.go new file mode 100644 index 0000000000..493e216b9b --- /dev/null +++ b/go/genkithttp/exp/agent.go @@ -0,0 +1,169 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package exp + +import ( + "errors" + "fmt" + "strings" + + aix "github.com/genkit-ai/genkit-go/v2/ai/exp" + "github.com/genkit-ai/genkit-go/v2/core/api" + "github.com/genkit-ai/genkit-go/v2/genkithttp" +) + +// AgentOption configures [HandleAgent]. +type AgentOption interface { + applyAgent(*agentConfig) error +} + +type agentConfig struct { + path string + pathSet bool + hideGetSnapshot bool + hideWaitForSnapshot bool + hideAbort bool + routeOpts []genkithttp.RouteOption +} + +type agentOptionFunc func(*agentConfig) error + +func (f agentOptionFunc) applyAgent(c *agentConfig) error { return f(c) } + +// WithPath overrides the base path where [HandleAgent] mounts the agent +// (default: "/" + agent.Name()). Must start with "/" and not end with "/" +// unless "/". Companion routes are mounted at /getSnapshot, +// /waitForSnapshot, and /abort. +func WithPath(path string) AgentOption { + return agentOptionFunc(func(c *agentConfig) error { + if path == "" { + return errors.New("route path must not be empty") + } + if !strings.HasPrefix(path, "/") { + return fmt.Errorf("route path %q must start with \"/\"", path) + } + if len(path) > 1 && strings.HasSuffix(path, "/") { + return fmt.Errorf("route path %q must not end with \"/\"", path) + } + c.path = path + c.pathSet = true + return nil + }) +} + +// HideGetSnapshot prevents [HandleAgent] from mounting the /getSnapshot +// companion route even when the agent has a session store. +func HideGetSnapshot() AgentOption { + return agentOptionFunc(func(c *agentConfig) error { + c.hideGetSnapshot = true + return nil + }) +} + +// HideWaitForSnapshot prevents [HandleAgent] from mounting the +// /waitForSnapshot companion route even when the agent has a session +// store. +func HideWaitForSnapshot() AgentOption { + return agentOptionFunc(func(c *agentConfig) error { + c.hideWaitForSnapshot = true + return nil + }) +} + +// HideAbort prevents [HandleAgent] from mounting the /abort companion +// route even when the agent's session store supports abort. +func HideAbort() AgentOption { + return agentOptionFunc(func(c *agentConfig) error { + c.hideAbort = true + return nil + }) +} + +// WithRouteOptions forwards [genkithttp.RouteOption] values (such as +// [genkithttp.WithStreamManager], [genkithttp.WithMaxBodyBytes], +// [genkithttp.WithHeartbeat], and [genkithttp.WithOnError]) to the mounted +// agent routes. [genkithttp.WithStreamManager] applies only to the primary turn +// route; companion routes are always served without a stream manager. +func WithRouteOptions(opts ...genkithttp.RouteOption) AgentOption { + return agentOptionFunc(func(c *agentConfig) error { + c.routeOpts = append(c.routeOpts, opts...) + return nil + }) +} + +// HandleAgent mounts an agent's turn route and applicable companion routes on m: +// - POST (always — runs one turn, unary or SSE) +// - POST /getSnapshot (if agent.GetSnapshotAction() != nil, unless [HideGetSnapshot]) +// - POST /waitForSnapshot (if agent.WaitForSnapshotAction() != nil, unless [HideWaitForSnapshot]) +// - POST /abort (if agent.AbortAction() != nil, unless [HideAbort]) +// +// Default is "/" + agent.Name() (overridable via [WithPath]). +// Panics if m is nil, agent is nil, any option is invalid, or any route path +// conflicts with an existing route on m. +func HandleAgent[S any](m *genkithttp.Mux, agent *aix.Agent[S], opts ...AgentOption) { + if m == nil { + panic("genkithttp/exp.HandleAgent: mux is nil") + } + if agent == nil { + panic("genkithttp/exp.HandleAgent: agent is nil") + } + + var cfg agentConfig + for _, opt := range opts { + if opt == nil { + continue + } + if err := opt.applyAgent(&cfg); err != nil { + panic(fmt.Errorf("genkithttp/exp.HandleAgent: %w", err)) + } + } + + basePath := cfg.path + if !cfg.pathSet { + basePath = "/" + agent.Name() + } + + turnOpts := make([]genkithttp.RouteOption, 0, len(cfg.routeOpts)+1) + turnOpts = append(turnOpts, cfg.routeOpts...) + turnOpts = append(turnOpts, genkithttp.WithPath(basePath)) + genkithttp.HandleAction(m, agent, turnOpts...) + + mountCompanion := func(suffix string, action api.Action) { + if action == nil { + return + } + path := basePath + suffix + if basePath == "/" { + path = suffix + } + compOpts := make([]genkithttp.RouteOption, 0, len(cfg.routeOpts)+2) + compOpts = append(compOpts, cfg.routeOpts...) + // Durable stream managers apply only to the primary turn route. + compOpts = append(compOpts, genkithttp.WithStreamManager(nil), genkithttp.WithPath(path)) + genkithttp.HandleAction(m, action, compOpts...) + } + + if !cfg.hideGetSnapshot { + mountCompanion("/getSnapshot", agent.GetSnapshotAction()) + } + if !cfg.hideWaitForSnapshot { + mountCompanion("/waitForSnapshot", agent.WaitForSnapshotAction()) + } + if !cfg.hideAbort { + mountCompanion("/abort", agent.AbortAction()) + } +} diff --git a/go/genkithttp/exp/agent_test.go b/go/genkithttp/exp/agent_test.go new file mode 100644 index 0000000000..21ce5cba3e --- /dev/null +++ b/go/genkithttp/exp/agent_test.go @@ -0,0 +1,480 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package exp_test + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync/atomic" + "testing" + + genkit "github.com/genkit-ai/genkit-go/v2" + "github.com/genkit-ai/genkit-go/v2/ai" + aix "github.com/genkit-ai/genkit-go/v2/ai/exp" + "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" + "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/core/x/streaming" + genkitx "github.com/genkit-ai/genkit-go/v2/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" +) + +type agentHTTPResult struct { + FinishReason string `json:"finishReason"` + SessionID string `json:"sessionId"` + SnapshotID string `json:"snapshotId"` + Message *ai.Message `json:"message"` + State json.RawMessage `json:"state"` + Error *struct { + Status string `json:"status"` + Message string `json:"message"` + Details map[string]any `json:"details"` + } `json:"error"` +} + +type snapshotHTTPResult struct { + SnapshotID string `json:"snapshotId"` + SessionID string `json:"sessionId"` + Status string `json:"status"` + State json.RawMessage `json:"state"` +} + +// nonAbortableStore wraps a SessionStore without exposing SnapshotSubscriber, +// so agents using it have getSnapshot/waitForSnapshot but no abort companion. +type nonAbortableStore[S any] struct { + inner aix.SessionStore[S] +} + +func (s *nonAbortableStore[S]) GetSnapshot(ctx context.Context, snapshotID string) (*aix.SessionSnapshot[S], error) { + return s.inner.GetSnapshot(ctx, snapshotID) +} +func (s *nonAbortableStore[S]) GetLatestSnapshot(ctx context.Context, sessionID string) (*aix.SessionSnapshot[S], error) { + return s.inner.GetLatestSnapshot(ctx, sessionID) +} +func (s *nonAbortableStore[S]) SaveSnapshot(ctx context.Context, snapshotID string, fn func(existing *aix.SessionSnapshot[S]) (*aix.SessionSnapshot[S], error)) (*aix.SessionSnapshot[S], error) { + return s.inner.SaveSnapshot(ctx, snapshotID, fn) +} + +func routePatterns(routes []genkithttp.Route) []string { + out := make([]string, len(routes)) + for i, r := range routes { + out[i] = r.Pattern() + } + return out +} + +func TestHandleAgent_RoutesAndOptions(t *testing.T) { + g := genkit.MustInit(context.Background(), genkit.WithExperimental()) + genkit.DefineModel(g, "test/echo", &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true}}, + func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { + return &ai.ModelResponse{ + Message: ai.NewModelTextMessage("ok"), + FinishReason: ai.FinishReasonStop, + }, nil + }) + + clientAgent := genkitx.DefineAgent[any](g, "clientAgent", aix.InlinePrompt{ai.WithModelName("test/echo")}) + + abortableStore, err := localstore.NewFileSessionStore[any](t.TempDir()) + if err != nil { + t.Fatal(err) + } + serverAgent := genkitx.DefineAgent(g, "serverAgent", aix.InlinePrompt{ai.WithModelName("test/echo")}, + aix.WithSessionStore(abortableStore)) + + nonAbortAgent := genkitx.DefineAgent(g, "nonAbortAgent", aix.InlinePrompt{ai.WithModelName("test/echo")}, + aix.WithSessionStore[any](&nonAbortableStore[any]{inner: localstore.NewInMemorySessionStore[any]()})) + + t.Run("client-managed registers turn route only", func(t *testing.T) { + m := genkithttp.NewMux() + genkithttpx.HandleAgent(m, clientAgent) + + want := []string{"POST /clientAgent"} + if got := routePatterns(m.Routes()); !slices.Equal(got, want) { + t.Errorf("routes = %v, want %v", got, want) + } + }) + + t.Run("abortable store-backed registers turn + all companions", func(t *testing.T) { + m := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttpx.HandleAgent(m, serverAgent) + + want := []string{ + "POST /api/serverAgent", + "POST /api/serverAgent/getSnapshot", + "POST /api/serverAgent/waitForSnapshot", + "POST /api/serverAgent/abort", + } + if got := routePatterns(m.Routes()); !slices.Equal(got, want) { + t.Errorf("routes = %v, want %v", got, want) + } + }) + + t.Run("non-abortable store-backed omits abort route", func(t *testing.T) { + m := genkithttp.NewMux() + genkithttpx.HandleAgent(m, nonAbortAgent) + + want := []string{ + "POST /nonAbortAgent", + "POST /nonAbortAgent/getSnapshot", + "POST /nonAbortAgent/waitForSnapshot", + } + if got := routePatterns(m.Routes()); !slices.Equal(got, want) { + t.Errorf("routes = %v, want %v", got, want) + } + }) + + t.Run("Hide options and WithPath control mounted routes", func(t *testing.T) { + m := genkithttp.NewMux() + genkithttpx.HandleAgent(m, serverAgent, + genkithttpx.WithPath("/chat"), + genkithttpx.HideGetSnapshot(), + genkithttpx.HideWaitForSnapshot(), + ) + want := []string{"POST /chat", "POST /chat/abort"} + if got := routePatterns(m.Routes()); !slices.Equal(got, want) { + t.Errorf("routes = %v, want %v", got, want) + } + + m2 := genkithttp.NewMux() + genkithttpx.HandleAgent(m2, serverAgent, + genkithttpx.WithPath("/"), + genkithttpx.HideAbort(), + ) + want2 := []string{"POST /", "POST /getSnapshot", "POST /waitForSnapshot"} + if got := routePatterns(m2.Routes()); !slices.Equal(got, want2) { + t.Errorf("root routes = %v, want %v", got, want2) + } + }) + + t.Run("WithRouteOptions applies StreamManager only to turn route", func(t *testing.T) { + sm := streaming.NewInMemoryStreamManager() + defer sm.Close() + + m := genkithttp.NewMux() + genkithttpx.HandleAgent(m, serverAgent, + genkithttpx.WithRouteOptions( + genkithttp.WithStreamManager(sm), + genkithttp.WithHeartbeat(0), + ), + ) + + // Primary turn route receives X-Genkit-Stream-Id on SSE. + turnReq := httptest.NewRequest(http.MethodPost, "/serverAgent?stream=true", + strings.NewReader(`{"data":{"message":{"role":"user","content":[{"text":"hi"}]}}}`)) + wTurn := httptest.NewRecorder() + m.ServeHTTP(wTurn, turnReq) + if wTurn.Code != http.StatusOK { + t.Fatalf("turn status = %d, body = %s", wTurn.Code, wTurn.Body.String()) + } + if wTurn.Header().Get(genkithttp.HeaderStreamID) == "" { + t.Error("expected X-Genkit-Stream-Id on primary turn route") + } + + // Companion route does NOT open a durable stream. + snapReq := httptest.NewRequest(http.MethodPost, "/serverAgent/getSnapshot?stream=true", + strings.NewReader(`{"data":{"snapshotId":"nope"}}`)) + wSnap := httptest.NewRecorder() + m.ServeHTTP(wSnap, snapReq) + if wSnap.Header().Get(genkithttp.HeaderStreamID) != "" { + t.Errorf("companion route unexpectedly set X-Genkit-Stream-Id = %q", wSnap.Header().Get(genkithttp.HeaderStreamID)) + } + }) +} + +type ctxRecordingStore struct { + inner *localstore.InMemorySessionStore[any] + key genkit.ContextKey[string] + lastSaveUID atomic.Value + lastGetUID atomic.Value +} + +func (s *ctxRecordingStore) SaveSnapshot(ctx context.Context, snapshotID string, fn func(existing *aix.SessionSnapshot[any]) (*aix.SessionSnapshot[any], error)) (*aix.SessionSnapshot[any], error) { + if uid, ok := s.key.FromContext(ctx); ok { + s.lastSaveUID.Store(uid) + } + return s.inner.SaveSnapshot(ctx, snapshotID, fn) +} + +func (s *ctxRecordingStore) GetSnapshot(ctx context.Context, snapshotID string) (*aix.SessionSnapshot[any], error) { + if uid, ok := s.key.FromContext(ctx); ok { + s.lastGetUID.Store(uid) + } + return s.inner.GetSnapshot(ctx, snapshotID) +} + +func (s *ctxRecordingStore) GetLatestSnapshot(ctx context.Context, sessionID string) (*aix.SessionSnapshot[any], error) { + return s.inner.GetLatestSnapshot(ctx, sessionID) +} + +func TestHandleAgent_EndToEndLifecycleAndAuth(t *testing.T) { + g := genkit.MustInit(context.Background(), genkit.WithExperimental()) + var modelCalls atomic.Int64 + userKey := genkit.NewContextKey[string]("uid") + + recStore := &ctxRecordingStore{ + inner: localstore.NewInMemorySessionStore[any](), + key: userKey, + } + + genkit.DefineModel(g, "test/echo", &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true}}, + func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { + modelCalls.Add(1) + last := req.Messages[len(req.Messages)-1] + if last.Role == ai.RoleUser && strings.Contains(last.Text(), "fail") { + return nil, status.Errorf(status.ErrResourceExhausted, "model on fire") + } + uid, _ := userKey.FromContext(ctx) + if cb != nil { + _ = cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("chunk")}}) + } + return &ai.ModelResponse{ + Message: ai.NewModelTextMessage(fmt.Sprintf("echo %d (%s)", len(req.Messages), uid)), + FinishReason: ai.FinishReasonStop, + }, nil + }) + + clientAgent := genkitx.DefineAgent[any](g, "agentClient", aix.InlinePrompt{ai.WithModelName("test/echo")}) + + fileStore, err := localstore.NewFileSessionStore[any](t.TempDir()) + if err != nil { + t.Fatal(err) + } + serverAgent := genkitx.DefineAgent(g, "agentServer", aix.InlinePrompt{ai.WithModelName("test/echo")}, + aix.WithSessionStore(fileStore)) + ctxAgent := genkitx.DefineAgent(g, "agentCtx", aix.InlinePrompt{ai.WithModelName("test/echo")}, + aix.WithSessionStore[any](recStore)) + + apiMux := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttpx.HandleAgent(apiMux, clientAgent) + genkithttpx.HandleAgent(apiMux, serverAgent) + genkithttpx.HandleAgent(apiMux, ctxAgent) + + // Wrapping Mux with auth middleware protects turn AND all companion routes. + requireAuth := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tok := r.Header.Get("Authorization") + if !strings.HasPrefix(tok, "Bearer ") { + genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "sign in required")) + return + } + uid := strings.TrimPrefix(tok, "Bearer ") + next.ServeHTTP(w, r.WithContext(userKey.WithValue(r.Context(), uid))) + }) + } + handler := requireAuth(apiMux) + + post := func(t *testing.T, path, body, token string, stream bool) (int, http.Header, string) { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if stream { + req.Header.Set("Accept", "text/event-stream") + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + resp := w.Result() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, resp.Header, string(b) + } + + parseResult := func(t *testing.T, body string) agentHTTPResult { + t.Helper() + var env struct { + Result agentHTTPResult `json:"result"` + } + if err := json.Unmarshal([]byte(body), &env); err != nil { + t.Fatalf("unmarshal %q: %v", body, err) + } + return env.Result + } + + parseSnapshot := func(t *testing.T, body string) snapshotHTTPResult { + t.Helper() + var env struct { + Result snapshotHTTPResult `json:"result"` + } + if err := json.Unmarshal([]byte(body), &env); err != nil { + t.Fatalf("unmarshal %q: %v", body, err) + } + return env.Result + } + + turn := func(text string) string { + return `{"data":{"message":{"role":"user","content":[{"text":"` + text + `"}]}}}` + } + turnWithInit := func(text, init string) string { + return `{"data":{"message":{"role":"user","content":[{"text":"` + text + `"}]}},"init":` + init + `}` + } + + t.Run("auth middleware protects turn and all companion routes", func(t *testing.T) { + for _, path := range []string{ + "/api/agentServer", + "/api/agentServer/getSnapshot", + "/api/agentServer/waitForSnapshot", + "/api/agentServer/abort", + } { + code, _, body := post(t, path, `{"data":{}}`, "", false) + if code != http.StatusUnauthorized { + t.Errorf("%s without auth: status = %d, want 401; body = %s", path, code, body) + } + } + }) + + t.Run("client-managed conversation resumes across requests with auth context", func(t *testing.T) { + code, _, body := post(t, "/api/agentClient", turn("hello"), "alice", false) + if code != http.StatusOK { + t.Fatalf("status = %d, body = %s", code, body) + } + res := parseResult(t, body) + if res.Message.Text() != "echo 1 (alice)" || len(res.State) == 0 { + t.Fatalf("unexpected first turn: %+v", res) + } + + code, _, body = post(t, "/api/agentClient", turnWithInit("again", `{"state":`+string(res.State)+`}`), "alice", false) + if code != http.StatusOK { + t.Fatalf("resume status = %d, body = %s", code, body) + } + res2 := parseResult(t, body) + if res2.Message.Text() != "echo 3 (alice)" { + t.Errorf("resumed message = %q, want %q", res2.Message.Text(), "echo 3 (alice)") + } + }) + + t.Run("server-managed detached turn, getSnapshot, waitForSnapshot, abort, and redaction", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + + // Failure redaction on served turn & snapshot. + code, _, body := post(t, "/api/agentServer", turn("fail"), "bob", false) + if code != http.StatusOK { + t.Fatalf("fail turn status = %d, body = %s", code, body) + } + failed := parseResult(t, body) + if failed.Error == nil || failed.Error.Status != "RESOURCE_EXHAUSTED" { + t.Fatalf("error = %+v, want RESOURCE_EXHAUSTED", failed.Error) + } + if strings.Contains(failed.Error.Message, "model on fire") { + t.Errorf("turn output leaked internal error: %q", failed.Error.Message) + } + _, _, snapBody := post(t, "/api/agentServer/getSnapshot", `{"data":{"snapshotId":"`+failed.SnapshotID+`"}}`, "bob", false) + if strings.Contains(snapBody, "model on fire") || !strings.Contains(snapBody, "RESOURCE_EXHAUSTED") { + t.Errorf("getSnapshot leaked internal error: %s", snapBody) + } + + // Detached turn followed via waitForSnapshot and abort (no-op on terminal). + code, _, body = post(t, "/api/agentServer", + `{"data":{"detach":true,"message":{"role":"user","content":[{"text":"work"}]}}}`, "bob", false) + if code != http.StatusOK { + t.Fatalf("detach status = %d, body = %s", code, body) + } + det := parseResult(t, body) + if det.FinishReason != "detached" || det.SnapshotID == "" { + t.Fatalf("detached = %+v", det) + } + + code, _, body = post(t, "/api/agentServer/waitForSnapshot", `{"data":{"snapshotId":"`+det.SnapshotID+`"}}`, "bob", false) + if code != http.StatusOK { + t.Fatalf("waitForSnapshot status = %d, body = %s", code, body) + } + snap := parseSnapshot(t, body) + if snap.Status != "completed" { + t.Errorf("waitForSnapshot status = %q, want completed", snap.Status) + } + + code, _, body = post(t, "/api/agentServer/abort", `{"data":{"snapshotId":"`+det.SnapshotID+`"}}`, "bob", false) + if code != http.StatusOK { + t.Fatalf("abort status = %d, body = %s", code, body) + } + if got := parseSnapshot(t, body).Status; got != "completed" { + t.Errorf("abort terminal status = %q, want completed", got) + } + }) + + t.Run("streaming turn delivers chunks and trace headers", func(t *testing.T) { + code, hdr, body := post(t, "/api/agentClient", turn("stream"), "carol", true) + if code != http.StatusOK { + t.Fatalf("status = %d, body = %s", code, body) + } + if hdr.Get(genkithttp.HeaderTraceID) == "" || hdr.Get(genkithttp.HeaderSpanID) == "" { + t.Error("missing trace/span headers on streaming agent turn") + } + if !strings.Contains(body, "modelChunk") || !strings.Contains(body, `"result"`) { + t.Errorf("unexpected SSE body: %s", body) + } + }) + + t.Run("auth context propagates into SessionStore Save and Get", func(t *testing.T) { + code, _, body := post(t, "/api/agentCtx", turn("store-check"), "dana", false) + if code != http.StatusOK { + t.Fatalf("turn status = %d, body = %s", code, body) + } + res := parseResult(t, body) + if got, _ := recStore.lastSaveUID.Load().(string); got != "dana" { + t.Errorf("SessionStore.Save saw uid = %q, want dana", got) + } + + code, _, body = post(t, "/api/agentCtx/getSnapshot", `{"data":{"snapshotId":"`+res.SnapshotID+`"}}`, "dana", false) + if code != http.StatusOK { + t.Fatalf("getSnapshot status = %d, body = %s", code, body) + } + if got, _ := recStore.lastGetUID.Load().(string); got != "dana" { + t.Errorf("SessionStore.Get saw uid = %q, want dana", got) + } + }) +} + +func TestHandleAgent_Panics(t *testing.T) { + g := genkit.MustInit(context.Background(), genkit.WithExperimental()) + genkit.DefineModel(g, "test/echo", &ai.ModelOptions{}, + func(ctx context.Context, req *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) { + return &ai.ModelResponse{Message: ai.NewModelTextMessage("ok"), FinishReason: ai.FinishReasonStop}, nil + }) + agent := genkitx.DefineAgent[any](g, "a", aix.InlinePrompt{ai.WithModelName("test/echo")}) + + cases := []struct { + name string + fn func() + }{ + {"nil mux", func() { genkithttpx.HandleAgent(nil, agent) }}, + {"nil agent", func() { genkithttpx.HandleAgent[any](genkithttp.NewMux(), nil) }}, + {"invalid path", func() { genkithttpx.HandleAgent(genkithttp.NewMux(), agent, genkithttpx.WithPath("bad")) }}, + {"trailing slash path", func() { genkithttpx.HandleAgent(genkithttp.NewMux(), agent, genkithttpx.WithPath("/bad/")) }}, + {"duplicate mount", func() { + m := genkithttp.NewMux() + genkithttpx.HandleAgent(m, agent) + genkithttpx.HandleAgent(m, agent) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic for %s", tc.name) + } + }() + tc.fn() + }) + } +} diff --git a/go/genkithttp/exp/doc.go b/go/genkithttp/exp/doc.go new file mode 100644 index 0000000000..5f95c5cb6a --- /dev/null +++ b/go/genkithttp/exp/doc.go @@ -0,0 +1,35 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +/* +Package exp provides experimental HTTP routing helpers built on top of +[github.com/genkit-ai/genkit-go/v2/genkithttp] for serving experimental Genkit +primitives such as agents. + +It is commonly imported under the alias genkithttpx: + + import ( + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" + ) + + api := genkithttp.NewMux() + genkithttpx.HandleAgent(api, weatherAgent) + +Keeping agent HTTP routing in this experimental subpackage decouples stable +[genkithttp] from [github.com/genkit-ai/genkit-go/v2/ai/exp]. +*/ +package exp diff --git a/go/genkithttp/handler.go b/go/genkithttp/handler.go new file mode 100644 index 0000000000..4becf8c6e5 --- /dev/null +++ b/go/genkithttp/handler.go @@ -0,0 +1,395 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "sync" + "sync/atomic" + "time" + + "github.com/google/uuid" + + "github.com/genkit-ai/genkit-go/v2/core/api" + "github.com/genkit-ai/genkit-go/v2/core/logger" + "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/core/tracing" + "github.com/genkit-ai/genkit-go/v2/core/x/streaming" + "github.com/genkit-ai/genkit-go/v2/internal/wire" +) + +var requestID atomic.Int64 + +// NewHandler returns an [http.Handler] serving a single Genkit action (flow, +// model, prompt, agent, etc.) over the Genkit HTTP wire protocol (unary JSON + +// SSE). Panics if a is nil or any option is invalid. +func NewHandler(a api.Action, opts ...HandlerOption) http.Handler { + if a == nil { + panic("genkithttp.NewHandler: action is nil") + } + cfg := defaultHandlerConfig() + for _, opt := range opts { + if opt == nil { + continue + } + if err := opt.applyHandler(&cfg); err != nil { + panic(fmt.Errorf("genkithttp.NewHandler: %w", err)) + } + } + return newActionHandler(a, cfg) +} + +type actionHandler struct { + action api.Action + key string + cfg handlerConfig +} + +func newActionHandler(a api.Action, cfg handlerConfig) *actionHandler { + return &actionHandler{ + action: a, + key: a.Desc().Key, + cfg: cfg, + } +} + +func (h *actionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + log := logger.FromContext(r.Context()).With("reqId", requestID.Add(1)) + r = r.WithContext(logger.WithContext(r.Context(), log)) + ctx := r.Context() + + start := time.Now() + logger.Debug(ctx, "request started", "method", r.Method, "path", r.URL.Path) + + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + err := &httpStatusError{ + httpCode: http.StatusMethodNotAllowed, + err: status.PublicErrorf(status.ErrInvalidArgument, "method %s not allowed", r.Method), + } + h.handlePreStreamError(ctx, w, r, err, start) + return + } + + stream, err := WantsStream(r) + if err != nil { + h.handlePreStreamError(ctx, w, r, err, start) + return + } + + // Reconnect to an existing durable stream before decoding a request body, + // since reconnect requests may omit or send an empty body. + if stream { + if streamID := r.Header.Get(HeaderStreamID); streamID != "" && h.cfg.streamManager != nil { + h.subscribeToStream(ctx, w, r, streamID, start) + return + } + } + + body, err := DecodeRequest(w, r, h.cfg.maxBodyBytes) + if err != nil { + h.handlePreStreamError(ctx, w, r, err, start) + return + } + + // Reject init on non-bidi actions before committing SSE headers so the + // client receives an HTTP 400 rather than a 200 OK SSE error frame. + if err := wire.CheckInitSupported(h.action, body.Init); err != nil { + h.handlePreStreamError(ctx, w, r, err, start) + return + } + + // Mark the context so actions (such as agents) apply served-wire error + // redaction outside dev mode. + actionCtx := wire.WithServedAction(ctx, h.key) + + if stream { + if h.cfg.streamManager != nil { + h.serveDurableStream(actionCtx, w, r, body, start) + return + } + h.serveStream(actionCtx, w, r, body, start) + return + } + + h.serveUnary(actionCtx, w, r, body, start) +} + +func (h *actionHandler) serveUnary(ctx context.Context, w http.ResponseWriter, r *http.Request, body *Request, start time.Time) { + res, err := wire.RunActionWithOptionalInit(ctx, h.action, body.Data, body.Init, nil) + if res.TraceID != "" { + w.Header().Set(HeaderTraceID, res.TraceID) + } + if res.SpanID != "" { + w.Header().Set(HeaderSpanID, res.SpanID) + } + if err != nil { + h.handlePreStreamError(ctx, w, r, err, start) + return + } + if err := WriteResult(w, res.Output); err != nil { + logger.Debug(ctx, "failed to write unary result", "error", err) + return + } + logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) +} + +func (h *actionHandler) serveStream(ctx context.Context, w http.ResponseWriter, r *http.Request, body *Request, start time.Time) { + sse := NewSSEWriter(w) + defer sse.Close() + + var startOnce sync.Once + startSSE := func(traceID, spanID string) { + startOnce.Do(func() { + _ = sse.startWithTraceHeaders(traceID, spanID) + sse.StartHeartbeat(h.cfg.heartbeat) + }) + } + + actionCtx := tracing.WithTelemetryCallback(ctx, startSSE) + cb := func(_ context.Context, msg json.RawMessage) error { + return sse.WriteMessage(msg) + } + + res, err := wire.RunActionWithOptionalInit(actionCtx, h.action, body.Data, body.Init, cb) + sse.Close() + + if err != nil { + if clientDisconnected(ctx, err) { + h.logDisconnect(ctx, r, err, start) + return + } + if !sse.Started() { + if res.TraceID != "" { + w.Header().Set(HeaderTraceID, res.TraceID) + } + if res.SpanID != "" { + w.Header().Set(HeaderSpanID, res.SpanID) + } + h.handlePreStreamError(ctx, w, r, err, start) + return + } + h.handleMidStreamError(ctx, sse, r, err, start) + return + } + + // Ensure trace headers are set even for custom actions that did not invoke + // the telemetry callback during execution. + if !sse.Started() && (res.TraceID != "" || res.SpanID != "") { + startSSE(res.TraceID, res.SpanID) + sse.Close() + } + + if err := sse.WriteResult(res.Output); err != nil { + logger.Debug(ctx, "failed to write SSE result", "error", err) + return + } + logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) +} + +func (h *actionHandler) serveDurableStream(ctx context.Context, w http.ResponseWriter, r *http.Request, body *Request, start time.Time) { + streamID := uuid.New().String() + durableStream, err := h.cfg.streamManager.Open(ctx, streamID) + if err != nil { + h.handlePreStreamError(ctx, w, r, err, start) + return + } + + w.Header().Set(HeaderStreamID, streamID) + sse := NewSSEWriter(w) + + // Detach execution from the HTTP request lifecycle while preserving request + // values (auth, logger, telemetry), bounded by WithStreamTimeout. + runCtx := context.WithoutCancel(ctx) + var cancelTimeout context.CancelFunc + if h.cfg.streamTimeout > 0 { + runCtx, cancelTimeout = context.WithTimeout(runCtx, h.cfg.streamTimeout) + } + + var startOnce sync.Once + startSSE := func(traceID, spanID string) { + startOnce.Do(func() { + _ = sse.startWithTraceHeaders(traceID, spanID) + sse.StartHeartbeat(h.cfg.heartbeat) + }) + } + runCtx = tracing.WithTelemetryCallback(runCtx, startSSE) + + type runOutcome struct { + res api.RunResult + err error + } + done := make(chan runOutcome, 1) + + go func() { + defer durableStream.Close() + if cancelTimeout != nil { + defer cancelTimeout() + } + + cb := func(_ context.Context, msg json.RawMessage) error { + _ = durableStream.Write(runCtx, msg) + _ = sse.WriteMessage(msg) + return nil + } + + res, runErr := wire.RunActionWithOptionalInit(runCtx, h.action, body.Data, body.Init, cb) + if runErr != nil { + _ = durableStream.Error(runCtx, runErr) + } else { + _ = durableStream.Done(runCtx, res.Output) + } + done <- runOutcome{res: res, err: runErr} + }() + + select { + case outcome := <-done: + sse.Close() + if outcome.err != nil { + if !sse.Started() { + w.Header().Del(HeaderStreamID) + if outcome.res.TraceID != "" { + w.Header().Set(HeaderTraceID, outcome.res.TraceID) + } + if outcome.res.SpanID != "" { + w.Header().Set(HeaderSpanID, outcome.res.SpanID) + } + h.handlePreStreamError(ctx, w, r, outcome.err, start) + return + } + h.handleMidStreamError(ctx, sse, r, outcome.err, start) + return + } + if !sse.Started() && (outcome.res.TraceID != "" || outcome.res.SpanID != "") { + startSSE(outcome.res.TraceID, outcome.res.SpanID) + sse.Close() + } + if err := sse.WriteResult(outcome.res.Output); err != nil { + logger.Debug(ctx, "failed to write SSE result", "error", err) + return + } + logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) + + case <-ctx.Done(): + // Client disconnected: detach from w so the background goroutine never + // touches the ResponseWriter after ServeHTTP returns, while continuing + // to stream into durable storage up to streamTimeout. + sse.detach() + h.logDisconnect(ctx, r, ctx.Err(), start) + } +} + +func (h *actionHandler) subscribeToStream(ctx context.Context, w http.ResponseWriter, r *http.Request, streamID string, start time.Time) { + events, unsubscribe, err := h.cfg.streamManager.Subscribe(ctx, streamID) + if err != nil { + if status.Of(err) == status.NotFound { + w.WriteHeader(http.StatusNoContent) + return + } + h.handlePreStreamError(ctx, w, r, err, start) + return + } + defer unsubscribe() + + w.Header().Set(HeaderStreamID, streamID) + sse := NewSSEWriter(w) + defer sse.Close() + + if err := sse.Start(); err != nil { + logger.Debug(ctx, "failed to start SSE stream", "error", err) + return + } + sse.StartHeartbeat(h.cfg.heartbeat) + + for { + select { + case <-ctx.Done(): + h.logDisconnect(ctx, r, ctx.Err(), start) + return + case event, ok := <-events: + if !ok { + logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) + return + } + switch event.Type { + case streaming.StreamEventChunk: + if err := sse.WriteMessage(event.Chunk); err != nil { + logger.Debug(ctx, "failed to write SSE chunk", "error", err) + return + } + case streaming.StreamEventDone: + sse.Close() + if err := sse.WriteResult(event.Output); err != nil { + logger.Debug(ctx, "failed to write SSE result", "error", err) + return + } + logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) + return + case streaming.StreamEventError: + sse.Close() + streamErr := event.Err + if streamErr == nil { + streamErr = errors.New("unknown error") + } + h.handleMidStreamError(ctx, sse, r, streamErr, start) + return + } + } + } +} + +func (h *actionHandler) handlePreStreamError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error, start time.Time) { + if clientDisconnected(ctx, err) { + h.logDisconnect(ctx, r, err, start) + return + } + logger.Error(ctx, "request failed", + "method", r.Method, + "path", r.URL.Path, + "duration", time.Since(start).Round(time.Millisecond), + "error", err) + if h.cfg.onError != nil { + h.cfg.onError(ctx, r, err) + } + h.cfg.encodeError(w, r, err) +} + +func (h *actionHandler) handleMidStreamError(ctx context.Context, sse *SSEWriter, r *http.Request, err error, start time.Time) { + logger.Error(ctx, "streaming request failed", + "method", r.Method, + "path", r.URL.Path, + "duration", time.Since(start).Round(time.Millisecond), + "error", err) + if h.cfg.onError != nil { + h.cfg.onError(ctx, r, err) + } + if werr := sse.WriteError(err); werr != nil { + logger.Debug(ctx, "failed to write SSE error", "error", werr) + } +} + +func (h *actionHandler) logDisconnect(ctx context.Context, r *http.Request, err error, start time.Time) { + logger.Debug(ctx, "client disconnected", + "method", r.Method, + "path", r.URL.Path, + "duration", time.Since(start).Round(time.Millisecond), + "error", err) +} diff --git a/go/genkithttp/handler_test.go b/go/genkithttp/handler_test.go new file mode 100644 index 0000000000..d38e3988ab --- /dev/null +++ b/go/genkithttp/handler_test.go @@ -0,0 +1,1006 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + genkit "github.com/genkit-ai/genkit-go/v2" + "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/core/api" + "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/core/x/streaming" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + "github.com/genkit-ai/genkit-go/v2/internal/wire" +) + +func decodeWireError(t *testing.T, body []byte) wire.Error { + t.Helper() + var e wire.Error + if err := json.Unmarshal(body, &e); err != nil { + t.Fatalf("error body %q is not a JSON wire error: %v", body, err) + } + return e +} + +func TestNewHandler_PanicsOnInvalidArgs(t *testing.T) { + g := genkit.MustInit(context.Background()) + flow := genkit.DefineFlow(g, "validFlow", func(ctx context.Context, in string) (string, error) { + return in, nil + }) + + cases := []struct { + name string + fn func() + }{ + {"nil action", func() { genkithttp.NewHandler(nil) }}, + {"negative heartbeat", func() { genkithttp.NewHandler(flow, genkithttp.WithHeartbeat(-time.Second)) }}, + {"negative stream timeout", func() { genkithttp.NewHandler(flow, genkithttp.WithStreamTimeout(-time.Second)) }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic for %s", tc.name) + } + }() + tc.fn() + }) + } +} + +func TestHandler_RequestDecodingAndHTTPCompliance(t *testing.T) { + g := genkit.MustInit(context.Background()) + + echoFlow := genkit.DefineFlow(g, "echo", func(ctx context.Context, in string) (string, error) { + return "echo:" + in, nil + }) + emptyFlow := genkit.DefineFlow(g, "empty", func(ctx context.Context, _ struct{}) (string, error) { + return "ok", nil + }) + + t.Run("unary POST with valid JSON returns 200 and trace headers", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow) + req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"data":"hello"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + + resp := w.Result() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", resp.StatusCode, body) + } + if ct := resp.Header.Get("Content-Type"); ct != "application/json" { + t.Errorf("Content-Type = %q, want application/json", ct) + } + if resp.Header.Get(genkithttp.HeaderTraceID) == "" { + t.Error("missing X-Genkit-Trace-Id header on unary response") + } + if resp.Header.Get(genkithttp.HeaderSpanID) == "" { + t.Error("missing X-Genkit-Span-Id header on unary response") + } + var out struct { + Result string `json:"result"` + } + if err := json.Unmarshal(body, &out); err != nil { + t.Fatalf("unmarshal response %q: %v", body, err) + } + if out.Result != "echo:hello" { + t.Errorf("result = %q, want %q", out.Result, "echo:hello") + } + }) + + t.Run("chunked / HTTP2 request body (ContentLength == -1) decodes properly", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow) + req := httptest.NewRequest(http.MethodPost, "/echo", io.NopCloser(strings.NewReader(`{"data":"chunked-payload"}`))) + req.ContentLength = -1 + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + + resp := w.Result() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", resp.StatusCode, body) + } + if !strings.Contains(string(body), `"echo:chunked-payload"`) { + t.Errorf("body = %q, want chunked payload decoded", body) + } + }) + + t.Run("empty bodies succeed", func(t *testing.T) { + h := genkithttp.NewHandler(emptyFlow) + for _, tc := range []struct { + name string + body io.Reader + }{ + {"nil body", nil}, + {"http.NoBody", http.NoBody}, + {"0-byte body", strings.NewReader("")}, + } { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/empty", tc.body) + if tc.body == nil { + req.Body = nil + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Errorf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + }) + } + }) + + t.Run("oversized body exceeding WithMaxBodyBytes returns 413", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow, genkithttp.WithMaxBodyBytes(16)) + req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"data":"this payload is way over 16 bytes"}`)) + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + + if w.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413; body = %s", w.Code, w.Body.String()) + } + wireErr := decodeWireError(t, w.Body.Bytes()) + if wireErr.Status != status.InvalidArgument { + t.Errorf("wire status = %q, want INVALID_ARGUMENT", wireErr.Status) + } + }) + + t.Run("WithMaxBodyBytes(0) disables limit", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow, genkithttp.WithMaxBodyBytes(0)) + big := strings.Repeat("a", 1024) + req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"data":"`+big+`"}`)) + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + }) + + t.Run("malformed JSON returns 400 INVALID_ARGUMENT", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow) + req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"data":invalid}`)) + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) + } + wireErr := decodeWireError(t, w.Body.Bytes()) + if wireErr.Status != status.InvalidArgument { + t.Errorf("wire status = %q, want INVALID_ARGUMENT", wireErr.Status) + } + }) + + t.Run("non-POST methods return 405 with Allow: POST", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow) + for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete, http.MethodPatch} { + t.Run(method, func(t *testing.T) { + req := httptest.NewRequest(method, "/echo", nil) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusMethodNotAllowed { + t.Errorf("status = %d, want 405", w.Code) + } + if got := w.Header().Get("Allow"); got != http.MethodPost { + t.Errorf("Allow = %q, want POST", got) + } + wireErr := decodeWireError(t, w.Body.Bytes()) + if wireErr.Status != status.InvalidArgument { + t.Errorf("wire status = %q, want INVALID_ARGUMENT", wireErr.Status) + } + }) + } + }) + + t.Run("init on non-bidi flow returns 400 before SSE", func(t *testing.T) { + h := genkithttp.NewHandler(echoFlow) + for _, stream := range []bool{false, true} { + req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"data":"hi","init":{"k":"v"}}`)) + if stream { + req.Header.Set("Accept", "text/event-stream") + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("stream=%v: status = %d, want 400; body = %s", stream, w.Code, w.Body.String()) + } + if ct := w.Header().Get("Content-Type"); strings.Contains(ct, "text/event-stream") { + t.Errorf("stream=%v: Content-Type = %q; must not commit SSE before rejecting init", stream, ct) + } + } + }) +} + +func TestHandler_BidiInitEnvelope(t *testing.T) { + type cfg struct { + Prefix string `json:"prefix"` + } + bidi := core.NewBidiAction(api.ActionTypeCustom, "bidiEcho", nil, + func(ctx context.Context, c cfg, inCh <-chan string, outCh chan<- string) (string, error) { + for in := range inCh { + outCh <- c.Prefix + in + } + return "done", nil + }) + h := genkithttp.NewHandler(bidi) + + t.Run("unary with init", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"hi","init":{"prefix":">> "}}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"done"`) { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + }) + + t.Run("streaming with init delivers prefixed chunk", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"hi","init":{"prefix":"PFX:"}}`)) + req.Header.Set("Accept", "text/event-stream") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + if !strings.Contains(w.Body.String(), `"PFX:hi"`) || !strings.Contains(w.Body.String(), `"done"`) { + t.Errorf("unexpected SSE body: %s", w.Body.String()) + } + }) + + t.Run("malformed init returns 400 even on streaming request", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"hi","init":{"prefix":42}}`)) + req.Header.Set("Accept", "text/event-stream") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) + } + if ct := w.Header().Get("Content-Type"); strings.Contains(ct, "text/event-stream") { + t.Errorf("Content-Type = %q; must not commit SSE on pre-stream init decode error", ct) + } + }) +} + +// wrappedResponseWriter wraps an http.ResponseWriter using Go 1.20+ Unwrap() +// without implementing http.Flusher directly, simulating middleware like +// otelhttp or Chi/Gin/Echo wrappers. +type wrappedResponseWriter struct { + inner *trackingResponseWriter + directFlushCalled bool +} + +func (w *wrappedResponseWriter) Header() http.Header { return w.inner.Header() } +func (w *wrappedResponseWriter) Write(b []byte) (int, error) { return w.inner.Write(b) } +func (w *wrappedResponseWriter) WriteHeader(code int) { w.inner.WriteHeader(code) } +func (w *wrappedResponseWriter) Unwrap() http.ResponseWriter { return w.inner } + +type trackingResponseWriter struct { + *httptest.ResponseRecorder + mu sync.Mutex + flushCount int + writeDeadlineCalls int + lastWriteDeadline time.Time +} + +func (t *trackingResponseWriter) Flush() { + t.mu.Lock() + t.flushCount++ + t.mu.Unlock() + t.ResponseRecorder.Flush() +} + +func (t *trackingResponseWriter) SetWriteDeadline(d time.Time) error { + t.mu.Lock() + t.writeDeadlineCalls++ + t.lastWriteDeadline = d + t.mu.Unlock() + return nil +} + +func TestHandler_SSEStreaming(t *testing.T) { + g := genkit.MustInit(context.Background()) + + streamFlow := genkit.DefineStreamingFlow(g, "letters", + func(ctx context.Context, input string, cb func(context.Context, string) error) (string, error) { + for _, r := range input { + if err := cb(ctx, string(r)); err != nil { + return "", err + } + } + return input + "-end", nil + }) + + t.Run("Accept and query negotiation", func(t *testing.T) { + h := genkithttp.NewHandler(streamFlow) + triggers := []struct { + name string + url string + accept []string + }{ + {"query param", "/letters?stream=true", nil}, + {"exact Accept", "/letters", []string{"text/event-stream"}}, + {"Accept with quality", "/letters", []string{"text/event-stream, application/json;q=0.9"}}, + {"Accept with charset", "/letters", []string{"text/event-stream; charset=utf-8"}}, + {"multiple Accept headers", "/letters", []string{"application/json", "text/event-stream"}}, + } + + for _, tc := range triggers { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, tc.url, strings.NewReader(`{"data":"ab"}`)) + for _, a := range tc.accept { + req.Header.Add("Accept", a) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + resp := w.Result() + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200", resp.StatusCode) + } + if got := resp.Header.Get("Content-Type"); got != "text/event-stream" { + t.Errorf("Content-Type = %q, want text/event-stream", got) + } + if got := resp.Header.Get("Cache-Control"); got != "no-cache, no-transform" { + t.Errorf("Cache-Control = %q, want no-cache, no-transform", got) + } + if got := resp.Header.Get("X-Accel-Buffering"); got != "no" { + t.Errorf("X-Accel-Buffering = %q, want no", got) + } + // HTTP/2 forbidden headers must NOT be set. + if got := resp.Header.Get("Connection"); got != "" { + t.Errorf("Connection header set to %q, must be empty", got) + } + if got := resp.Header.Get("Transfer-Encoding"); got != "" { + t.Errorf("Transfer-Encoding header set to %q, must be empty", got) + } + // Trace headers must be set on SSE responses too. + if resp.Header.Get(genkithttp.HeaderTraceID) == "" { + t.Error("missing X-Genkit-Trace-Id header on SSE response") + } + if resp.Header.Get(genkithttp.HeaderSpanID) == "" { + t.Error("missing X-Genkit-Span-Id header on SSE response") + } + + want := "data: {\"message\":\"a\"}\n\ndata: {\"message\":\"b\"}\n\ndata: {\"result\":\"ab-end\"}\n\n" + if string(body) != want { + t.Errorf("body =\n%q\nwant:\n%q", string(body), want) + } + }) + } + }) + + t.Run("invalid stream query param returns 400", func(t *testing.T) { + h := genkithttp.NewHandler(streamFlow) + req := httptest.NewRequest(http.MethodPost, "/letters?stream=nope", strings.NewReader(`{"data":"a"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400; body = %s", w.Code, w.Body.String()) + } + }) + + t.Run("flushes and clears write deadline through wrapped ResponseWriter", func(t *testing.T) { + h := genkithttp.NewHandler(streamFlow, genkithttp.WithHeartbeat(0)) + inner := &trackingResponseWriter{ResponseRecorder: httptest.NewRecorder()} + wrapped := &wrappedResponseWriter{inner: inner} + + req := httptest.NewRequest(http.MethodPost, "/letters?stream=true", strings.NewReader(`{"data":"abc"}`)) + h.ServeHTTP(wrapped, req) + + // At least: 1 on Start + 3 chunks + 1 result = 5 flushes. + if inner.flushCount < 5 { + t.Errorf("flushCount = %d, want >= 5 (ResponseController must unwrap middleware writer)", inner.flushCount) + } + if inner.writeDeadlineCalls != 1 || !inner.lastWriteDeadline.IsZero() { + t.Errorf("SetWriteDeadline calls = %d (last=%v), want 1 call with zero time", inner.writeDeadlineCalls, inner.lastWriteDeadline) + } + }) + + t.Run("heartbeats emitted during slow execution without races", func(t *testing.T) { + slowFlow := genkit.DefineStreamingFlow(g, "slowHeartbeats", + func(ctx context.Context, _ string, cb func(context.Context, string) error) (string, error) { + time.Sleep(80 * time.Millisecond) + if err := cb(ctx, "chunk1"); err != nil { + return "", err + } + time.Sleep(50 * time.Millisecond) + return "done", nil + }) + + h := genkithttp.NewHandler(slowFlow, genkithttp.WithHeartbeat(15*time.Millisecond)) + req := httptest.NewRequest(http.MethodPost, "/slow?stream=true", strings.NewReader(`{"data":"go"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + body := w.Body.String() + if !strings.Contains(body, ": keepalive\n\n") { + t.Errorf("expected keepalive comment frame in body, got:\n%s", body) + } + if !strings.Contains(body, `data: {"message":"chunk1"}`) || !strings.Contains(body, `data: {"result":"done"}`) { + t.Errorf("missing chunk or result in body:\n%s", body) + } + }) + + t.Run("mid-stream error emits SSE error frame and invokes OnError without ErrorEncoder", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + sentinel := errors.New("secret database credentials failed") + failFlow := genkit.DefineStreamingFlow(g, "midStreamFail", + func(ctx context.Context, _ string, cb func(context.Context, string) error) (string, error) { + _ = cb(ctx, "partial") + return "", sentinel + }) + + var onErrCalled error + encoderCalled := false + h := genkithttp.NewHandler(failFlow, + genkithttp.WithHeartbeat(0), + genkithttp.WithOnError(func(_ context.Context, _ *http.Request, err error) { + onErrCalled = err + }), + genkithttp.WithErrorEncoder(func(w http.ResponseWriter, r *http.Request, err error) { + encoderCalled = true + genkithttp.WriteError(w, err) + }), + ) + + req := httptest.NewRequest(http.MethodPost, "/fail?stream=true", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Errorf("status = %d, want 200 (headers already committed)", w.Code) + } + if encoderCalled { + t.Error("ErrorEncoder must not be invoked for mid-stream errors") + } + if !errors.Is(onErrCalled, sentinel) { + t.Errorf("OnError got %v, want original unredacted %v", onErrCalled, sentinel) + } + body := w.Body.String() + if strings.Contains(body, "secret database") { + t.Errorf("mid-stream SSE frame leaked internal error: %s", body) + } + wantErrFrame := `data: {"error":{"status":"INTERNAL","message":"internal"}}` + if !strings.Contains(body, wantErrFrame) { + t.Errorf("body =\n%s\nwant error frame %s", body, wantErrFrame) + } + }) +} + +func TestHandler_ErrorRedactionAndCallbacks(t *testing.T) { + g := genkit.MustInit(context.Background()) + + providerFlow := genkit.DefineFlow(g, "leakProvider", func(ctx context.Context, _ string) (string, error) { + return "", status.Errorf(status.Base(status.FromHTTPCode(429)), + "googleapi: Error 429: Quota exceeded for project 12345678, model projects/acme-prod/locations/us/models/x") + }) + outputFlow := genkit.DefineFlow(g, "leakOutput", func(ctx context.Context, _ string) (string, error) { + return "", status.Errorf(status.ErrInvalidOutput, + "invalid output: - ssn: Invalid type") + }) + unclassifiedFlow := genkit.DefineFlow(g, "leakUnclassified", func(ctx context.Context, _ string) (string, error) { + return "", errors.New("dial tcp 10.0.0.7:5432: connection refused") + }) + publicFlow := genkit.DefineFlow(g, "publicErr", func(ctx context.Context, _ string) (string, error) { + return "", status.PublicErrorf(status.ErrPermissionDenied, "upgrade to pro plan") + }) + + t.Run("redacts internal details outside dev while passing original to OnError", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + cases := []struct { + name string + flow api.Action + code int + secrets []string + }{ + {"provider 429", providerFlow, http.StatusTooManyRequests, []string{"acme-prod", "12345678"}}, + {"output schema", outputFlow, http.StatusInternalServerError, []string{"ssn"}}, + {"unclassified", unclassifiedFlow, http.StatusInternalServerError, []string{"10.0.0.7", "connection refused"}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var observed error + h := genkithttp.NewHandler(tc.flow, genkithttp.WithOnError(func(_ context.Context, _ *http.Request, err error) { + observed = err + })) + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != tc.code { + t.Errorf("status = %d, want %d", w.Code, tc.code) + } + if observed == nil { + t.Fatal("OnError was not called") + } + for _, s := range tc.secrets { + if strings.Contains(w.Body.String(), s) { + t.Errorf("response body leaked %q: %s", s, w.Body.String()) + } + if !strings.Contains(observed.Error(), s) { + t.Errorf("OnError err = %q, want unredacted substring %q", observed.Error(), s) + } + } + }) + } + }) + + t.Run("public error preserves status and message", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + h := genkithttp.NewHandler(publicFlow) + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusForbidden { + t.Errorf("status = %d, want 403", w.Code) + } + got := decodeWireError(t, w.Body.Bytes()) + if got.Status != status.PermissionDenied || got.Message != "upgrade to pro plan" { + t.Errorf("wire error = %+v, want PERMISSION_DENIED / upgrade to pro plan", got) + } + }) + + t.Run("dev environment preserves full internal message", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "dev") + h := genkithttp.NewHandler(unclassifiedFlow) + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if !strings.Contains(w.Body.String(), "10.0.0.7:5432") { + t.Errorf("dev body = %q, want full message", w.Body.String()) + } + }) + + t.Run("WriteError standalone helper handles public, internal, typed nil, and MaxBytesError", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + + w := httptest.NewRecorder() + genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "sign in required")) + if w.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want 401", w.Code) + } + if got := decodeWireError(t, w.Body.Bytes()); got.Status != status.Unauthenticated || got.Message != "sign in required" { + t.Errorf("got %+v", got) + } + + // Typed nil *status.Error must never report 200 OK. + var typedNil *status.Error + w2 := httptest.NewRecorder() + genkithttp.WriteError(w2, error(typedNil)) + if w2.Code != http.StatusInternalServerError { + t.Errorf("typed nil status = %d, want 500", w2.Code) + } + if got := decodeWireError(t, w2.Body.Bytes()); got.Status != status.Internal { + t.Errorf("typed nil wire status = %q, want INTERNAL", got.Status) + } + + // MaxBytesError -> 413. + w3 := httptest.NewRecorder() + genkithttp.WriteError(w3, &http.MaxBytesError{Limit: 10}) + if w3.Code != http.StatusRequestEntityTooLarge { + t.Errorf("MaxBytesError status = %d, want 413", w3.Code) + } + }) + + t.Run("WithErrorEncoder overrides pre-stream error formatting", func(t *testing.T) { + h := genkithttp.NewHandler(publicFlow, genkithttp.WithErrorEncoder(func(w http.ResponseWriter, _ *http.Request, err error) { + w.WriteHeader(http.StatusTeapot) + _, _ = w.Write([]byte("custom:" + err.Error())) + })) + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusTeapot || w.Body.String() != "custom:upgrade to pro plan" { + t.Errorf("got status=%d body=%q", w.Code, w.Body.String()) + } + }) +} + +type recordingHandler struct { + mu sync.Mutex + records []slog.Record +} + +func (h *recordingHandler) Enabled(context.Context, slog.Level) bool { return true } +func (h *recordingHandler) Handle(_ context.Context, r slog.Record) error { + h.mu.Lock() + defer h.mu.Unlock() + h.records = append(h.records, r.Clone()) + return nil +} +func (h *recordingHandler) WithAttrs([]slog.Attr) slog.Handler { return h } +func (h *recordingHandler) WithGroup(string) slog.Handler { return h } + +func (h *recordingHandler) messages(level slog.Level) []string { + h.mu.Lock() + defer h.mu.Unlock() + var msgs []string + for _, r := range h.records { + if r.Level == level { + msgs = append(msgs, r.Message) + } + } + return msgs +} + +func TestHandler_ClientDisconnectLogging(t *testing.T) { + g := genkit.MustInit(context.Background()) + + defineFlow := func(name string, selfCancel bool, started chan<- struct{}) api.Action { + return genkit.DefineStreamingFlow(g, name, + func(ctx context.Context, _ string, cb func(context.Context, string) error) (string, error) { + if cb != nil { + if err := cb(ctx, "chunk"); err != nil { + return "", err + } + } + close(started) + if selfCancel { + return "", context.Canceled + } + <-ctx.Done() + return "", ctx.Err() + }) + } + + tests := []struct { + name string + stream bool + selfCancel bool + wantError bool + }{ + {name: "streaming client disconnects", stream: true}, + {name: "non-streaming client disconnects"}, + {name: "streaming flow cancels itself", stream: true, selfCancel: true, wantError: true}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := &recordingHandler{} + prev := slog.Default() + slog.SetDefault(slog.New(rec)) + t.Cleanup(func() { slog.SetDefault(prev) }) + + started := make(chan struct{}) + h := genkithttp.NewHandler(defineFlow(fmt.Sprintf("disconnect%d", i), tt.selfCancel, started), genkithttp.WithHeartbeat(0)) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/", strings.NewReader(`{"data":"x"}`)) + if tt.stream { + req.Header.Set("Accept", "text/event-stream") + } + + done := make(chan struct{}) + go func() { + defer close(done) + h.ServeHTTP(httptest.NewRecorder(), req) + }() + <-started + if !tt.selfCancel { + cancel() + } + <-done + + errs := rec.messages(slog.LevelError) + if tt.wantError { + if len(errs) == 0 { + t.Fatal("no ERROR record for a cancellation the flow raised itself") + } + return + } + if len(errs) > 0 { + t.Errorf("ERROR records for a client disconnect: %q", errs) + } + debug := rec.messages(slog.LevelDebug) + if n := len(slices.DeleteFunc(slices.Clone(debug), func(m string) bool { return m != "client disconnected" })); n != 1 { + t.Errorf("DEBUG records = %q, want exactly one %q", debug, "client disconnected") + } + }) + } +} + +type tenantStreamManager struct { + inner streaming.StreamManager + tenantKey genkit.ContextKey[string] + mu sync.Mutex + owners map[string]string +} + +func (m *tenantStreamManager) Open(ctx context.Context, streamID string) (streaming.StreamInput, error) { + tenant, _ := m.tenantKey.FromContext(ctx) + m.mu.Lock() + m.owners[streamID] = tenant + m.mu.Unlock() + return m.inner.Open(ctx, streamID) +} + +func (m *tenantStreamManager) Subscribe(ctx context.Context, streamID string) (<-chan streaming.StreamEvent, func(), error) { + tenant, _ := m.tenantKey.FromContext(ctx) + m.mu.Lock() + owner, ok := m.owners[streamID] + m.mu.Unlock() + if ok && owner != tenant { + return nil, nil, status.PublicErrorf(status.ErrPermissionDenied, "stream belongs to another tenant") + } + return m.inner.Subscribe(ctx, streamID) +} + +func TestHandler_DurableStreaming(t *testing.T) { + g := genkit.MustInit(context.Background()) + + streamingFlow := genkit.DefineStreamingFlow(g, "durableFlow", + func(ctx context.Context, input string, cb func(context.Context, string) error) (string, error) { + for _, c := range input { + if err := cb(ctx, string(c)); err != nil { + return "", err + } + } + return input + "-done", nil + }) + + t.Run("emits stream ID, replays on reconnect, enforces tenant context, returns 204 on unknown", func(t *testing.T) { + tenantKey := genkit.NewContextKey[string]("tenant") + inner := streaming.NewInMemoryStreamManager() + defer inner.Close() + sm := &tenantStreamManager{inner: inner, tenantKey: tenantKey, owners: map[string]string{}} + + h := genkithttp.NewHandler(streamingFlow, genkithttp.WithStreamManager(sm), genkithttp.WithHeartbeat(0)) + + // First request as tenant-A. + req1 := httptest.NewRequest(http.MethodPost, "/durable?stream=true", strings.NewReader(`{"data":"ab"}`)) + req1 = req1.WithContext(tenantKey.WithValue(req1.Context(), "tenant-A")) + w1 := httptest.NewRecorder() + h.ServeHTTP(w1, req1) + + streamID := w1.Header().Get(genkithttp.HeaderStreamID) + if streamID == "" { + t.Fatal("missing X-Genkit-Stream-Id header") + } + if w1.Header().Get(genkithttp.HeaderTraceID) == "" { + t.Error("missing X-Genkit-Trace-Id header on durable stream") + } + wantBody := "data: {\"message\":\"a\"}\n\ndata: {\"message\":\"b\"}\n\ndata: {\"result\":\"ab-done\"}\n\n" + if w1.Body.String() != wantBody { + t.Errorf("initial body =\n%q\nwant:\n%q", w1.Body.String(), wantBody) + } + + // Reconnect as tenant-B -> 403 PERMISSION_DENIED. + reqForbidden := httptest.NewRequest(http.MethodPost, "/durable?stream=true", nil) + reqForbidden.Header.Set(genkithttp.HeaderStreamID, streamID) + reqForbidden = reqForbidden.WithContext(tenantKey.WithValue(reqForbidden.Context(), "tenant-B")) + wForbidden := httptest.NewRecorder() + h.ServeHTTP(wForbidden, reqForbidden) + if wForbidden.Code != http.StatusForbidden { + t.Errorf("cross-tenant reconnect status = %d, want 403; body = %s", wForbidden.Code, wForbidden.Body.String()) + } + + // Reconnect as tenant-A -> replays all chunks + result. + req2 := httptest.NewRequest(http.MethodPost, "/durable?stream=true", nil) + req2.Header.Set(genkithttp.HeaderStreamID, streamID) + req2 = req2.WithContext(tenantKey.WithValue(req2.Context(), "tenant-A")) + w2 := httptest.NewRecorder() + h.ServeHTTP(w2, req2) + if w2.Code != http.StatusOK || w2.Body.String() != wantBody { + t.Errorf("replay status=%d body=%q, want 200 / %q", w2.Code, w2.Body.String(), wantBody) + } + + // Unknown stream ID -> 204 No Content. + req3 := httptest.NewRequest(http.MethodPost, "/durable?stream=true", nil) + req3.Header.Set(genkithttp.HeaderStreamID, "unknown-id") + w3 := httptest.NewRecorder() + h.ServeHTTP(w3, req3) + if w3.Code != http.StatusNoContent { + t.Errorf("unknown stream status = %d, want 204", w3.Code) + } + }) + + t.Run("enforces WithStreamTimeout on detached run after client disconnect", func(t *testing.T) { + started := make(chan struct{}) + var timedOut atomic.Bool + finished := make(chan struct{}) + + hangingFlow := genkit.DefineStreamingFlow(g, "hangingDurable", + func(ctx context.Context, _ string, cb func(context.Context, string) error) (string, error) { + defer close(finished) + _ = cb(ctx, "started") + close(started) + <-ctx.Done() + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + timedOut.Store(true) + } + return "", ctx.Err() + }) + + sm := streaming.NewInMemoryStreamManager() + defer sm.Close() + h := genkithttp.NewHandler(hangingFlow, + genkithttp.WithStreamManager(sm), + genkithttp.WithStreamTimeout(60*time.Millisecond), + genkithttp.WithHeartbeat(10*time.Millisecond), + ) + + reqCtx, cancelReq := context.WithCancel(context.Background()) + req := httptest.NewRequestWithContext(reqCtx, http.MethodPost, "/hang?stream=true", strings.NewReader(`{"data":"x"}`)) + w := httptest.NewRecorder() + + handlerDone := make(chan struct{}) + go func() { + defer close(handlerDone) + h.ServeHTTP(w, req) + }() + + <-started + // Disconnect HTTP client while flow is still running. + cancelReq() + select { + case <-handlerDone: + case <-time.After(time.Second): + t.Fatal("ServeHTTP did not return promptly after client disconnect") + } + + // Detached execution should be canceled by WithStreamTimeout. + select { + case <-finished: + case <-time.After(time.Second): + t.Fatal("detached durable flow was not bounded by WithStreamTimeout") + } + if !timedOut.Load() { + t.Error("expected detached flow context to fail with context.DeadlineExceeded") + } + }) +} + +func TestHandler_ContextPropagation(t *testing.T) { + g := genkit.MustInit(context.Background()) + + type plainKey struct{} + type user struct { + UID string `json:"uid"` + } + userKey := genkit.NewContextKey[user]("auth") + + tool := genkit.DefineTool(g, "readCtxTool", "reads context values", + func(ctx context.Context, _ struct{}) (string, error) { + u, ok := userKey.FromContext(ctx) + if !ok { + return "", errors.New("missing userKey") + } + plain, _ := ctx.Value(plainKey{}).(string) + return u.UID + ":" + plain, nil + }) + + flow := genkit.DefineFlow(g, "ctxFlow", func(ctx context.Context, _ string) (string, error) { + return tool.Run(ctx, struct{}{}) + }) + + // Standard HTTP middleware populates both plain context.WithValue and genkit.ContextKey. + mw := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue(r.Context(), plainKey{}, "plain-val") + ctx = userKey.WithValue(ctx, user{UID: "u-99"}) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } + + h := mw(genkithttp.NewHandler(flow)) + req := httptest.NewRequest(http.MethodPost, "/ctxFlow", strings.NewReader(`{"data":"go"}`)) + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) + } + if !strings.Contains(w.Body.String(), `"u-99:plain-val"`) { + t.Errorf("body = %q, want u-99:plain-val", w.Body.String()) + } + + // Verify Dev UI / reflection fallback through ActionContext when running flow directly. + devCtx := core.WithActionContext(context.Background(), core.ActionContext{ + "auth": map[string]any{"uid": "dev-ui-user"}, + }) + devCtx = context.WithValue(devCtx, plainKey{}, "dev") + got, err := flow.Run(devCtx, "go") + if err != nil { + t.Fatalf("flow.Run(devCtx): %v", err) + } + if got != "dev-ui-user:dev" { + t.Errorf("got %q, want %q", got, "dev-ui-user:dev") + } +} + +func TestLowLevelWireHelpers(t *testing.T) { + t.Run("WriteResult encodes JSON result envelope", func(t *testing.T) { + w := httptest.NewRecorder() + if err := genkithttp.WriteResult(w, map[string]int{"n": 7}); err != nil { + t.Fatalf("WriteResult: %v", err) + } + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/json" { + t.Errorf("status=%d ct=%q", w.Code, w.Header().Get("Content-Type")) + } + if strings.TrimSpace(w.Body.String()) != `{"result":{"n":7}}` { + t.Errorf("body = %q", w.Body.String()) + } + }) + + t.Run("SSEWriter frames messages, comments, result, and error", func(t *testing.T) { + w := httptest.NewRecorder() + sse := genkithttp.NewSSEWriter(w) + defer sse.Close() + + if err := sse.WriteComment("hello"); err != nil { + t.Fatal(err) + } + if err := sse.WriteMessage("chunk"); err != nil { + t.Fatal(err) + } + if err := sse.WriteResult(42); err != nil { + t.Fatal(err) + } + want := ": hello\n\ndata: {\"message\":\"chunk\"}\n\ndata: {\"result\":42}\n\n" + if w.Body.String() != want { + t.Errorf("got:\n%q\nwant:\n%q", w.Body.String(), want) + } + }) + + t.Run("DecodeRequest reads bytes without Content-Length", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", io.NopCloser(bytes.NewBufferString(`{"data":[1,2]}`))) + req.ContentLength = -1 + got, err := genkithttp.DecodeRequest(httptest.NewRecorder(), req, 1024) + if err != nil { + t.Fatalf("DecodeRequest: %v", err) + } + if string(got.Data) != `[1,2]` { + t.Errorf("Data = %s, want [1,2]", got.Data) + } + }) + + t.Run("WantsStream reports false for non-streaming request", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/flow", nil) + req.Header.Set("Accept", "application/json") + want, err := genkithttp.WantsStream(req) + if err != nil || want { + t.Errorf("WantsStream = (%v, %v), want (false, nil)", want, err) + } + }) +} diff --git a/go/genkithttp/mux.go b/go/genkithttp/mux.go new file mode 100644 index 0000000000..75e8d94413 --- /dev/null +++ b/go/genkithttp/mux.go @@ -0,0 +1,171 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "fmt" + "net/http" + "slices" + "strings" + "sync" + + "github.com/genkit-ai/genkit-go/v2/core/api" + "github.com/genkit-ai/genkit-go/v2/core/status" +) + +// Route describes a single mounted endpoint on a [Mux]. +type Route struct { + // Method is always "POST". + Method string + // Path is the full route path, including the Mux basePath if configured. + Path string + // Action is the action's descriptor key (e.g. a.Desc().Key). + Action string + // Handler serves the action and is ready to wrap with middleware or mount + // directly in any router. + Handler http.Handler +} + +// Pattern returns "METHOD PATH" (e.g. "POST /api/jokeFlow") for Go 1.22+ +// [http.ServeMux.Handle] / [http.ServeMux.HandleFunc]. +func (r Route) Pattern() string { + return r.Method + " " + r.Path +} + +// Mux is an exact-match HTTP router for Genkit actions and agents. +// It implements [http.Handler]. +type Mux struct { + mu sync.RWMutex + cfg muxConfig + routesByPath map[string]http.Handler // keyed by local path (without basePath) + routes []Route +} + +// NewMux creates an exact-match HTTP router for Genkit actions and agents. +// Panics if any option is invalid (e.g. malformed basePath). +func NewMux(opts ...MuxOption) *Mux { + cfg := defaultMuxConfig() + for _, opt := range opts { + if opt == nil { + continue + } + if err := opt.applyMux(&cfg); err != nil { + panic(fmt.Errorf("genkithttp.NewMux: %w", err)) + } + } + return &Mux{ + cfg: cfg, + routesByPath: make(map[string]http.Handler), + } +} + +// HandleAction mounts a on m at "/" + a.Name() (or the path set by [WithPath]). +// Panics on nil m, nil a, invalid path (must start with "/", must not end with +// "/" unless "/"), invalid option, or duplicate path registration. +func HandleAction(m *Mux, a api.Action, opts ...RouteOption) { + if m == nil { + panic("genkithttp.HandleAction: mux is nil") + } + if a == nil { + panic("genkithttp.HandleAction: action is nil") + } + + rcfg := routeConfig{ + handlerConfig: m.cfg.handlerConfig, + } + for _, opt := range opts { + if opt == nil { + continue + } + if err := opt.applyRoute(&rcfg); err != nil { + panic(fmt.Errorf("genkithttp.HandleAction: %w", err)) + } + } + + localPath := rcfg.path + if !rcfg.pathSet { + localPath = "/" + a.Name() + if err := validateRoutePath(localPath); err != nil { + panic(fmt.Errorf("genkithttp.HandleAction: invalid default path for action %q: %w", a.Name(), err)) + } + } + + fullPath := m.cfg.basePath + localPath + if localPath == "/" && m.cfg.basePath != "" { + fullPath = m.cfg.basePath + } + + h := newActionHandler(a, rcfg.handlerConfig) + + m.mu.Lock() + defer m.mu.Unlock() + if _, exists := m.routesByPath[localPath]; exists { + panic(fmt.Sprintf("genkithttp.HandleAction: duplicate route path %q", fullPath)) + } + m.routesByPath[localPath] = h + m.routes = append(m.routes, Route{ + Method: http.MethodPost, + Path: fullPath, + Action: a.Desc().Key, + Handler: h, + }) +} + +// ServeHTTP dispatches POST requests by exact path match (stripping basePath if +// configured). Returns 404 JSON on unknown paths and 405 JSON with "Allow: POST" +// on non-POST requests to matched paths. +func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) { + reqPath := r.URL.Path + if m.cfg.basePath != "" { + switch { + case reqPath == m.cfg.basePath: + reqPath = "/" + case strings.HasPrefix(reqPath, m.cfg.basePath+"/"): + reqPath = strings.TrimPrefix(reqPath, m.cfg.basePath) + default: + m.writeNotFound(w, r) + return + } + } + + m.mu.RLock() + h, ok := m.routesByPath[reqPath] + m.mu.RUnlock() + + if !ok { + m.writeNotFound(w, r) + return + } + h.ServeHTTP(w, r) +} + +func (m *Mux) writeNotFound(w http.ResponseWriter, r *http.Request) { + err := status.PublicErrorf(status.ErrNotFound, "not found") + if m.cfg.onError != nil { + m.cfg.onError(r.Context(), r, err) + } + m.cfg.encodeError(w, r, err) +} + +// Routes returns a deterministic snapshot of all mounted routes in registration +// order, suitable for logging, testing, or native per-route registration in +// frameworks like Gin, Echo, or Chi. +func (m *Mux) Routes() []Route { + m.mu.RLock() + defer m.mu.RUnlock() + return slices.Clone(m.routes) +} diff --git a/go/genkithttp/mux_test.go b/go/genkithttp/mux_test.go new file mode 100644 index 0000000000..5afde06618 --- /dev/null +++ b/go/genkithttp/mux_test.go @@ -0,0 +1,214 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp_test + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + genkit "github.com/genkit-ai/genkit-go/v2" + "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" +) + +func TestMux_RoutingAndBasePath(t *testing.T) { + g := genkit.MustInit(context.Background()) + + slashFlow := genkit.DefineFlow(g, "googleai/gemini-flash-latest", func(ctx context.Context, in string) (string, error) { + return "model:" + in, nil + }) + jokeFlow := genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, in string) (string, error) { + return "joke:" + in, nil + }) + + t.Run("exact match including action names with slashes", func(t *testing.T) { + m := genkithttp.NewMux() + genkithttp.HandleAction(m, slashFlow) + genkithttp.HandleAction(m, jokeFlow) + + req := httptest.NewRequest(http.MethodPost, "/googleai/gemini-flash-latest", strings.NewReader(`{"data":"hi"}`)) + w := httptest.NewRecorder() + m.ServeHTTP(w, req) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"model:hi"`) { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + + // Trailing slash is NOT a match (strict exact matching). + req2 := httptest.NewRequest(http.MethodPost, "/googleai/gemini-flash-latest/", strings.NewReader(`{"data":"hi"}`)) + w2 := httptest.NewRecorder() + m.ServeHTTP(w2, req2) + if w2.Code != http.StatusNotFound { + t.Errorf("trailing slash status = %d, want 404", w2.Code) + } + + // Unknown path returns 404 JSON wire error. + req3 := httptest.NewRequest(http.MethodPost, "/doesNotExist", strings.NewReader(`{"data":"hi"}`)) + w3 := httptest.NewRecorder() + m.ServeHTTP(w3, req3) + if w3.Code != http.StatusNotFound { + t.Errorf("unknown path status = %d, want 404", w3.Code) + } + if wireErr := decodeWireError(t, w3.Body.Bytes()); wireErr.Status != status.NotFound { + t.Errorf("404 wire status = %q, want NOT_FOUND", wireErr.Status) + } + + // Matched path with non-POST returns 405 with Allow: POST. + req4 := httptest.NewRequest(http.MethodGet, "/jokeFlow", nil) + w4 := httptest.NewRecorder() + m.ServeHTTP(w4, req4) + if w4.Code != http.StatusMethodNotAllowed { + t.Errorf("GET matched path status = %d, want 405", w4.Code) + } + if got := w4.Header().Get("Allow"); got != http.MethodPost { + t.Errorf("Allow = %q, want POST", got) + } + }) + + t.Run("WithBasePath strips prefix and reflects in Routes", func(t *testing.T) { + m := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttp.HandleAction(m, jokeFlow) + genkithttp.HandleAction(m, slashFlow, genkithttp.WithPath("/custom")) + + // Matched under /api. + req := httptest.NewRequest(http.MethodPost, "/api/jokeFlow", strings.NewReader(`{"data":"cats"}`)) + w := httptest.NewRecorder() + m.ServeHTTP(w, req) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"joke:cats"`) { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + + // Prefix collision (/apifoo/jokeFlow) must 404. + reqBad := httptest.NewRequest(http.MethodPost, "/apifoo/jokeFlow", strings.NewReader(`{"data":"cats"}`)) + wBad := httptest.NewRecorder() + m.ServeHTTP(wBad, reqBad) + if wBad.Code != http.StatusNotFound { + t.Errorf("/apifoo status = %d, want 404", wBad.Code) + } + + // Unprefixed path must 404. + reqNoPrefix := httptest.NewRequest(http.MethodPost, "/jokeFlow", strings.NewReader(`{"data":"cats"}`)) + wNoPrefix := httptest.NewRecorder() + m.ServeHTTP(wNoPrefix, reqNoPrefix) + if wNoPrefix.Code != http.StatusNotFound { + t.Errorf("unprefixed status = %d, want 404", wNoPrefix.Code) + } + + routes := m.Routes() + if len(routes) != 2 { + t.Fatalf("len(Routes) = %d, want 2", len(routes)) + } + if routes[0].Method != http.MethodPost || routes[0].Path != "/api/jokeFlow" || routes[0].Action != jokeFlow.Desc().Key || routes[0].Pattern() != "POST /api/jokeFlow" { + t.Errorf("route[0] = %+v", routes[0]) + } + if routes[1].Method != http.MethodPost || routes[1].Path != "/api/custom" || routes[1].Action != slashFlow.Desc().Key || routes[1].Pattern() != "POST /api/custom" { + t.Errorf("route[1] = %+v", routes[1]) + } + + // Mutating returned slice must not affect Mux. + routes[0].Path = "/mutated" + if got := m.Routes()[0].Path; got != "/api/jokeFlow" { + t.Errorf("Routes snapshot was mutated: got %q", got) + } + + // Per-route Handler works directly when mounted on stdlib ServeMux. + stdMux := http.NewServeMux() + for _, rt := range m.Routes() { + stdMux.Handle(rt.Pattern(), rt.Handler) + } + reqStd := httptest.NewRequest(http.MethodPost, "/api/custom", strings.NewReader(`{"data":"direct"}`)) + wStd := httptest.NewRecorder() + stdMux.ServeHTTP(wStd, reqStd) + if wStd.Code != http.StatusOK || !strings.Contains(wStd.Body.String(), `"model:direct"`) { + t.Errorf("stdMux status=%d body=%s", wStd.Code, wStd.Body.String()) + } + }) + + t.Run("root route under WithBasePath", func(t *testing.T) { + m := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttp.HandleAction(m, jokeFlow, genkithttp.WithPath("/")) + + if got := m.Routes()[0].Path; got != "/api" { + t.Errorf("Path = %q, want /api", got) + } + req := httptest.NewRequest(http.MethodPost, "/api", strings.NewReader(`{"data":"root"}`)) + w := httptest.NewRecorder() + m.ServeHTTP(w, req) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"joke:root"`) { + t.Errorf("status=%d body=%s", w.Code, w.Body.String()) + } + }) + + t.Run("Mux options serve as defaults and route options override", func(t *testing.T) { + m := genkithttp.NewMux(genkithttp.WithMaxBodyBytes(12)) + genkithttp.HandleAction(m, jokeFlow, genkithttp.WithPath("/small")) + genkithttp.HandleAction(m, jokeFlow, genkithttp.WithPath("/large"), genkithttp.WithMaxBodyBytes(1024)) + + payload := `{"data":"longer than 12 bytes"}` + wSmall := httptest.NewRecorder() + m.ServeHTTP(wSmall, httptest.NewRequest(http.MethodPost, "/small", strings.NewReader(payload))) + if wSmall.Code != http.StatusRequestEntityTooLarge { + t.Errorf("/small status = %d, want 413", wSmall.Code) + } + + wLarge := httptest.NewRecorder() + m.ServeHTTP(wLarge, httptest.NewRequest(http.MethodPost, "/large", strings.NewReader(payload))) + if wLarge.Code != http.StatusOK { + t.Errorf("/large status = %d, want 200", wLarge.Code) + } + }) +} + +func TestMux_Panics(t *testing.T) { + g := genkit.MustInit(context.Background()) + flow := genkit.DefineFlow(g, "panicFlow", func(ctx context.Context, in string) (string, error) { + return in, nil + }) + + cases := []struct { + name string + fn func() + }{ + {"empty basePath", func() { genkithttp.NewMux(genkithttp.WithBasePath("")) }}, + {"root basePath", func() { genkithttp.NewMux(genkithttp.WithBasePath("/")) }}, + {"basePath without leading slash", func() { genkithttp.NewMux(genkithttp.WithBasePath("api")) }}, + {"basePath with trailing slash", func() { genkithttp.NewMux(genkithttp.WithBasePath("/api/")) }}, + {"nil mux", func() { genkithttp.HandleAction(nil, flow) }}, + {"nil action", func() { genkithttp.HandleAction(genkithttp.NewMux(), nil) }}, + {"empty route path", func() { genkithttp.HandleAction(genkithttp.NewMux(), flow, genkithttp.WithPath("")) }}, + {"route path without leading slash", func() { genkithttp.HandleAction(genkithttp.NewMux(), flow, genkithttp.WithPath("no-leading-slash")) }}, + {"route path with trailing slash", func() { genkithttp.HandleAction(genkithttp.NewMux(), flow, genkithttp.WithPath("/trailing/")) }}, + {"duplicate route path", func() { + m := genkithttp.NewMux() + genkithttp.HandleAction(m, flow) + genkithttp.HandleAction(m, flow) + }}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic for %s", tc.name) + } + }() + tc.fn() + }) + } +} diff --git a/go/genkithttp/option.go b/go/genkithttp/option.go new file mode 100644 index 0000000000..b02342fb30 --- /dev/null +++ b/go/genkithttp/option.go @@ -0,0 +1,287 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/genkit-ai/genkit-go/v2/core/x/streaming" +) + +const ( + defaultMaxBodyBytes int64 = 10 << 20 // 10 MiB + defaultHeartbeat = 15 * time.Second + defaultStreamTimeout = 10 * time.Minute + defaultShutdownTimeout = 30 * time.Second + defaultReadHeaderTimeout = 10 * time.Second +) + +// HandlerOption configures a single-action handler created by [NewHandler]. +type HandlerOption interface { + applyHandler(*handlerConfig) error +} + +// MuxOption configures a [Mux] created by [NewMux]. +type MuxOption interface { + applyMux(*muxConfig) error +} + +// RouteOption configures a route registered with [HandleAction]. +type RouteOption interface { + applyRoute(*routeConfig) error +} + +// SharedOption satisfies [HandlerOption], [MuxOption], and [RouteOption] so +// common options work uniformly on [NewHandler], [NewMux] (as defaults), and +// [HandleAction] (as per-route overrides). +type SharedOption interface { + HandlerOption + MuxOption + RouteOption +} + +// ServerOption configures [ListenAndServe]. +type ServerOption interface { + applyServer(*serverConfig) error +} + +type handlerConfig struct { + streamManager streaming.StreamManager + maxBodyBytes int64 + heartbeat time.Duration + streamTimeout time.Duration + onError func(ctx context.Context, r *http.Request, err error) + errorEncoder func(w http.ResponseWriter, r *http.Request, err error) +} + +func defaultHandlerConfig() handlerConfig { + return handlerConfig{ + maxBodyBytes: defaultMaxBodyBytes, + heartbeat: defaultHeartbeat, + streamTimeout: defaultStreamTimeout, + errorEncoder: defaultErrorEncoder, + } +} + +func defaultErrorEncoder(w http.ResponseWriter, _ *http.Request, err error) { + WriteError(w, err) +} + +func (c *handlerConfig) encodeError(w http.ResponseWriter, r *http.Request, err error) { + if c.errorEncoder != nil { + c.errorEncoder(w, r, err) + return + } + WriteError(w, err) +} + +type muxConfig struct { + handlerConfig + basePath string +} + +func defaultMuxConfig() muxConfig { + return muxConfig{ + handlerConfig: defaultHandlerConfig(), + } +} + +type routeConfig struct { + handlerConfig + path string + pathSet bool +} + +type serverConfig struct { + shutdownTimeout time.Duration + readHeaderTimeout time.Duration +} + +func defaultServerConfig() serverConfig { + return serverConfig{ + shutdownTimeout: defaultShutdownTimeout, + readHeaderTimeout: defaultReadHeaderTimeout, + } +} + +type sharedOptionFunc func(*handlerConfig) error + +func (f sharedOptionFunc) applyHandler(c *handlerConfig) error { return f(c) } +func (f sharedOptionFunc) applyMux(c *muxConfig) error { return f(&c.handlerConfig) } +func (f sharedOptionFunc) applyRoute(c *routeConfig) error { return f(&c.handlerConfig) } + +type muxOptionFunc func(*muxConfig) error + +func (f muxOptionFunc) applyMux(c *muxConfig) error { return f(c) } + +type routeOptionFunc func(*routeConfig) error + +func (f routeOptionFunc) applyRoute(c *routeConfig) error { return f(c) } + +type serverOptionFunc func(*serverConfig) error + +func (f serverOptionFunc) applyServer(c *serverConfig) error { return f(c) } + +// WithStreamManager enables durable/resumable streaming via +// [HeaderStreamID] (X-Genkit-Stream-Id). Passing nil disables durable streaming +// on a route even when the parent [Mux] sets a default manager. +func WithStreamManager(sm streaming.StreamManager) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + c.streamManager = sm + return nil + }) +} + +// WithMaxBodyBytes limits the decoded request body size (default: 10 MiB). +// Values <= 0 disable the limit. Exceeding the limit returns HTTP 413. +func WithMaxBodyBytes(n int64) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + c.maxBodyBytes = n + return nil + }) +} + +// WithHeartbeat sets the interval for SSE keepalive comment frames +// (": keepalive\n\n"). Default: 15s. Pass 0 to disable heartbeats. +func WithHeartbeat(d time.Duration) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + if d < 0 { + return fmt.Errorf("heartbeat duration must be >= 0, got %v", d) + } + c.heartbeat = d + return nil + }) +} + +// WithStreamTimeout bounds detached execution duration when using a +// [streaming.StreamManager] (where [context.WithoutCancel] detaches from client +// disconnect). Default: 10m. Pass 0 for no timeout. +func WithStreamTimeout(d time.Duration) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + if d < 0 { + return fmt.Errorf("stream timeout must be >= 0, got %v", d) + } + c.streamTimeout = d + return nil + }) +} + +// WithOnError registers an observability callback invoked on every error (both +// pre-stream and mid-stream) with the original, unredacted error. It does not +// alter wire serialization. +func WithOnError(fn func(ctx context.Context, r *http.Request, err error)) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + c.onError = fn + return nil + }) +} + +// WithErrorEncoder overrides how pre-stream HTTP errors are written. +// Default: [WriteError]. Mid-stream errors after SSE headers are committed are +// always serialized as SSE `data: {"error": ...}` frames. +func WithErrorEncoder(fn func(w http.ResponseWriter, r *http.Request, err error)) SharedOption { + return sharedOptionFunc(func(c *handlerConfig) error { + if fn == nil { + c.errorEncoder = defaultErrorEncoder + } else { + c.errorEncoder = fn + } + return nil + }) +} + +// WithBasePath sets a path prefix stripped by [Mux] before route matching +// (e.g. "/api"). Omit when the outer router already strips the prefix +// (e.g. chi.Mount or http.StripPrefix). Must start with "/" and not end with +// "/". +func WithBasePath(prefix string) MuxOption { + return muxOptionFunc(func(c *muxConfig) error { + if err := validateBasePath(prefix); err != nil { + return err + } + c.basePath = prefix + return nil + }) +} + +// WithPath overrides the route path for [HandleAction] (default: "/" + +// a.Name()). Must start with "/" and not end with "/" unless "/". +func WithPath(path string) RouteOption { + return routeOptionFunc(func(c *routeConfig) error { + if err := validateRoutePath(path); err != nil { + return err + } + c.path = path + c.pathSet = true + return nil + }) +} + +// WithShutdownTimeout sets the maximum duration [ListenAndServe] waits for +// in-flight requests to drain on shutdown. Default: 30s. Pass 0 for no timeout. +func WithShutdownTimeout(d time.Duration) ServerOption { + return serverOptionFunc(func(c *serverConfig) error { + if d < 0 { + return fmt.Errorf("shutdown timeout must be >= 0, got %v", d) + } + c.shutdownTimeout = d + return nil + }) +} + +// WithReadHeaderTimeout sets [http.Server.ReadHeaderTimeout] for +// [ListenAndServe] (Slowloris defense). Default: 10s. Pass 0 to disable. +func WithReadHeaderTimeout(d time.Duration) ServerOption { + return serverOptionFunc(func(c *serverConfig) error { + if d < 0 { + return fmt.Errorf("read header timeout must be >= 0, got %v", d) + } + c.readHeaderTimeout = d + return nil + }) +} + +func validateBasePath(prefix string) error { + if prefix == "" { + return errors.New("base path must not be empty") + } + if !strings.HasPrefix(prefix, "/") { + return fmt.Errorf("base path %q must start with \"/\"", prefix) + } + if strings.HasSuffix(prefix, "/") { + return fmt.Errorf("base path %q must not end with \"/\"", prefix) + } + return nil +} + +func validateRoutePath(path string) error { + if path == "" { + return errors.New("route path must not be empty") + } + if !strings.HasPrefix(path, "/") { + return fmt.Errorf("route path %q must start with \"/\"", path) + } + if len(path) > 1 && strings.HasSuffix(path, "/") { + return fmt.Errorf("route path %q must not end with \"/\"", path) + } + return nil +} diff --git a/go/genkithttp/server.go b/go/genkithttp/server.go new file mode 100644 index 0000000000..c189ec54f2 --- /dev/null +++ b/go/genkithttp/server.go @@ -0,0 +1,117 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "syscall" + + "github.com/genkit-ai/genkit-go/v2/core/logger" +) + +func resolveListenAddr(addr string) string { + if addr != "" { + return addr + } + port := os.Getenv("PORT") + if port == "" { + port = "3400" + } + return "0.0.0.0:" + port +} + +func newHTTPServer(addr string, h http.Handler, cfg serverConfig) *http.Server { + return &http.Server{ + Addr: resolveListenAddr(addr), + Handler: h, + ReadHeaderTimeout: cfg.readHeaderTimeout, + // WriteTimeout is intentionally 0 so long-running SSE streams are not + // terminated mid-response. + } +} + +// ListenAndServe runs h until ctx is canceled or SIGINT/SIGTERM is received, +// then gracefully drains in-flight requests. +// +// If addr is "", it defaults to "0.0.0.0:$PORT" (or "0.0.0.0:3400" if PORT is +// unset). Sets [http.Server.ReadHeaderTimeout] (Slowloris defense) and leaves +// [http.Server.WriteTimeout] unset (0) so long-running SSE streams are not +// terminated. +func ListenAndServe(ctx context.Context, addr string, h http.Handler, opts ...ServerOption) error { + if h == nil { + return errors.New("genkithttp.ListenAndServe: handler is nil") + } + cfg := defaultServerConfig() + for _, opt := range opts { + if opt == nil { + continue + } + if err := opt.applyServer(&cfg); err != nil { + return fmt.Errorf("genkithttp.ListenAndServe: %w", err) + } + } + + srv := newHTTPServer(addr, h, cfg) + ln, err := net.Listen("tcp", srv.Addr) + if err != nil { + return fmt.Errorf("genkithttp.ListenAndServe: listen %q: %w", srv.Addr, err) + } + + return serve(ctx, srv, ln, cfg) +} + +func serve(ctx context.Context, srv *http.Server, ln net.Listener, cfg serverConfig) error { + sigCtx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer stop() + + errCh := make(chan error, 1) + go func() { + logger.Info(ctx, "server listening", "addr", ln.Addr().String()) + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- fmt.Errorf("genkithttp.ListenAndServe: %w", err) + return + } + errCh <- nil + }() + + select { + case err := <-errCh: + return err + case <-sigCtx.Done(): + logger.Info(ctx, "server shutting down", "addr", ln.Addr().String()) + // Stop intercepting signals so a second interrupt kills the process + // immediately instead of being swallowed while requests drain. + stop() + + shutdownCtx := context.Background() + var cancel context.CancelFunc + if cfg.shutdownTimeout > 0 { + shutdownCtx, cancel = context.WithTimeout(shutdownCtx, cfg.shutdownTimeout) + defer cancel() + } + if err := srv.Shutdown(shutdownCtx); err != nil { + return fmt.Errorf("genkithttp.ListenAndServe: shutdown: %w", err) + } + return <-errCh + } +} diff --git a/go/genkithttp/wire.go b/go/genkithttp/wire.go new file mode 100644 index 0000000000..8fc8ae34b0 --- /dev/null +++ b/go/genkithttp/wire.go @@ -0,0 +1,395 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package genkithttp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/internal/wire" +) + +// Standard Genkit HTTP headers. +const ( + HeaderTraceID = "X-Genkit-Trace-Id" + HeaderSpanID = "X-Genkit-Span-Id" + HeaderStreamID = "X-Genkit-Stream-Id" +) + +// DefaultAllowedHeaders returns a fresh slice of request headers required by +// Genkit clients: Content-Type, Accept, Authorization, X-Genkit-Stream-Id. +func DefaultAllowedHeaders() []string { + return []string{"Content-Type", "Accept", "Authorization", HeaderStreamID} +} + +// DefaultExposedHeaders returns a fresh slice of response headers exposed to +// browser clients: X-Genkit-Trace-Id, X-Genkit-Span-Id, X-Genkit-Stream-Id. +func DefaultExposedHeaders() []string { + return []string{HeaderTraceID, HeaderSpanID, HeaderStreamID} +} + +// Request represents the Genkit HTTP wire request body. +type Request struct { + Data json.RawMessage `json:"data"` + Init json.RawMessage `json:"init,omitempty"` +} + +// httpStatusError overrides the HTTP status code written by [WriteError] while +// keeping the wrapped error's canonical Genkit status name and message. +type httpStatusError struct { + httpCode int + err error +} + +func (e *httpStatusError) Error() string { return e.err.Error() } +func (e *httpStatusError) Unwrap() error { return e.err } + +// DecodeRequest decodes a Genkit wire request body with an optional byte size +// limit. Passing maxBytes <= 0 disables the size limit. Handles chunked and +// HTTP/2 requests (where r.ContentLength == -1) as well as empty bodies. +// +// Exceeding maxBytes returns an error wrapping [*http.MaxBytesError], which +// [WriteError] maps to HTTP 413 Payload Too Large. Malformed JSON returns a +// public INVALID_ARGUMENT error (HTTP 400). +func DecodeRequest(w http.ResponseWriter, r *http.Request, maxBytes int64) (*Request, error) { + if r.Body == nil || r.Body == http.NoBody { + return &Request{}, nil + } + body := r.Body + defer body.Close() + if maxBytes > 0 { + body = http.MaxBytesReader(w, body, maxBytes) + } + + var req Request + if err := json.NewDecoder(body).Decode(&req); err != nil { + if errors.Is(err, io.EOF) { + return &Request{}, nil + } + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + return nil, status.PublicErrorf(status.ErrInvalidArgument, "request body too large").WithCause(maxErr) + } + return nil, status.PublicErrorf(status.ErrInvalidArgument, "%w", err) + } + return &req, nil +} + +// WantsStream reports whether the client requested SSE streaming via +// "?stream=true" or an Accept header containing media type "text/event-stream". +// Returns an INVALID_ARGUMENT error if "?stream" has an invalid boolean value. +func WantsStream(r *http.Request) (bool, error) { + if s := r.URL.Query().Get("stream"); s != "" { + b, err := strconv.ParseBool(s) + if err != nil { + return false, status.PublicErrorf(status.ErrInvalidArgument, "invalid stream query parameter: %w", err) + } + if b { + return true, nil + } + } + for _, headerVal := range r.Header.Values("Accept") { + for part := range strings.SplitSeq(headerVal, ",") { + mediaType, _, _ := strings.Cut(part, ";") + if strings.EqualFold(strings.TrimSpace(mediaType), "text/event-stream") { + return true, nil + } + } + } + return false, nil +} + +// WriteResult writes a 200 OK JSON response: {"result": result}. +func WriteResult(w http.ResponseWriter, result any) error { + data, err := json.Marshal(struct { + Result any `json:"result"` + }{Result: normalizeRawMessage(result)}) + if err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if _, err := w.Write(data); err != nil { + return err + } + _, err = w.Write([]byte("\n")) + return err +} + +// WriteError writes a redacted Genkit wire error JSON response with the HTTP +// status derived from status.Of(err).HTTPCode() (or 413 for +// [*http.MaxBytesError]). Safe for direct use inside standard HTTP auth +// middleware. +func WriteError(w http.ResponseWriter, err error) { + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + writeWireError(w, http.StatusRequestEntityTooLarge, status.InvalidArgument, "request body too large") + return + } + msg, code := clientError(err) + httpCode := code.HTTPCode() + var statusErr *httpStatusError + if errors.As(err, &statusErr) && statusErr.httpCode != 0 { + httpCode = statusErr.httpCode + } + writeWireError(w, httpCode, code, msg) +} + +func writeWireError(w http.ResponseWriter, httpCode int, code status.Name, msg string) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(httpCode) + _ = json.NewEncoder(w).Encode(wire.Error{Status: code, Message: msg}) +} + +// clientError returns the message and canonical status to send a client for +// err. Outside GENKIT_ENV=dev, non-public errors are redacted to generic +// status labels via [wire.ClientMessage]. +func clientError(err error) (string, status.Name) { + code := status.Of(err) + if code == status.OK { + code = status.Internal + } + msg, _ := wire.ClientMessage(err) + return msg, code +} + +// clientDisconnected reports whether err is the cancellation caused by the HTTP +// client closing the connection. +func clientDisconnected(ctx context.Context, err error) bool { + return errors.Is(err, context.Canceled) && errors.Is(ctx.Err(), context.Canceled) +} + +// normalizeRawMessage turns a non-nil empty json.RawMessage into nil so +// encoding/json marshals it as null instead of failing with unexpected EOF. +func normalizeRawMessage(v any) any { + if raw, ok := v.(json.RawMessage); ok && len(raw) == 0 { + return nil + } + return v +} + +// SSEWriter writes Genkit Server-Sent Events frames to an [http.ResponseWriter] +// using [http.ResponseController] for flushing and write-deadline clearing. +// All methods are safe for concurrent use. +type SSEWriter struct { + w http.ResponseWriter + rc *http.ResponseController + mu sync.Mutex + started bool + detached bool + + hbMu sync.Mutex + stopHB chan struct{} + hbDone chan struct{} +} + +// NewSSEWriter returns a new [SSEWriter] targeting w. Headers are not written +// until [SSEWriter.Start] or the first write method is called, allowing callers +// to set response headers (such as [HeaderTraceID], [HeaderSpanID], or +// [HeaderStreamID]) beforehand. +func NewSSEWriter(w http.ResponseWriter) *SSEWriter { + return &SSEWriter{ + w: w, + rc: http.NewResponseController(w), + } +} + +// Started reports whether SSE response headers have been committed. +func (s *SSEWriter) Started() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.started +} + +// Start commits the HTTP 200 SSE headers, clears the response write deadline if +// supported, and flushes. Calling Start more than once is a no-op. +func (s *SSEWriter) Start() error { + s.mu.Lock() + defer s.mu.Unlock() + return s.startLocked() +} + +func (s *SSEWriter) startWithTraceHeaders(traceID, spanID string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.detached || s.started { + return nil + } + if traceID != "" { + s.w.Header().Set(HeaderTraceID, traceID) + } + if spanID != "" { + s.w.Header().Set(HeaderSpanID, spanID) + } + return s.startLocked() +} + +func (s *SSEWriter) startLocked() error { + if s.detached || s.started { + return nil + } + s.w.Header().Set("Content-Type", "text/event-stream") + s.w.Header().Set("Cache-Control", "no-cache, no-transform") + s.w.Header().Set("X-Accel-Buffering", "no") + // Clear any server WriteTimeout so long-running SSE streams are not killed. + _ = s.rc.SetWriteDeadline(time.Time{}) + s.w.WriteHeader(http.StatusOK) + s.started = true + return ignoreUnsupported(s.rc.Flush()) +} + +// WriteMessage writes a streaming chunk frame: `data: {"message": }\n\n` +// and flushes. +func (s *SSEWriter) WriteMessage(msg any) error { + return s.writeEvent(struct { + Message any `json:"message"` + }{Message: normalizeRawMessage(msg)}) +} + +// WriteResult writes the final result frame: `data: {"result": }\n\n` +// and flushes. +func (s *SSEWriter) WriteResult(result any) error { + return s.writeEvent(struct { + Result any `json:"result"` + }{Result: normalizeRawMessage(result)}) +} + +// WriteError writes a redacted error frame: +// `data: {"error": {"status": "", "message": ""}}\n\n` and flushes. +func (s *SSEWriter) WriteError(err error) error { + msg, code := clientError(err) + return s.writeEvent(wire.ErrorResponse{ + Error: &wire.Error{Status: code, Message: msg}, + }) +} + +// WriteComment writes an SSE comment line (`: \n\n`) and flushes. +func (s *SSEWriter) WriteComment(comment string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.detached { + return nil + } + if err := s.startLocked(); err != nil { + return err + } + if _, err := fmt.Fprintf(s.w, ": %s\n\n", comment); err != nil { + return err + } + return ignoreUnsupported(s.rc.Flush()) +} + +func (s *SSEWriter) writeEvent(v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + if s.detached { + return nil + } + if err := s.startLocked(); err != nil { + return err + } + if _, err := fmt.Fprintf(s.w, "%s%s\n\n", wire.SSEDataPrefix, data); err != nil { + return err + } + return ignoreUnsupported(s.rc.Flush()) +} + +// StartHeartbeat begins sending `: keepalive\n\n` comment frames every interval +// until [SSEWriter.Close] is called. Values <= 0 are a no-op. +func (s *SSEWriter) StartHeartbeat(interval time.Duration) { + if interval <= 0 { + return + } + s.hbMu.Lock() + defer s.hbMu.Unlock() + + s.mu.Lock() + detached := s.detached + s.mu.Unlock() + if detached || s.stopHB != nil { + return + } + + stopCh := make(chan struct{}) + doneCh := make(chan struct{}) + s.stopHB = stopCh + s.hbDone = doneCh + + go func() { + defer close(doneCh) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + if err := s.WriteComment("keepalive"); err != nil { + return + } + case <-stopCh: + return + } + } + }() +} + +// Close stops any active heartbeat goroutine and waits for it to exit. +// It is safe to call multiple times. +func (s *SSEWriter) Close() { + s.hbMu.Lock() + stopCh := s.stopHB + doneCh := s.hbDone + s.stopHB = nil + s.hbDone = nil + s.hbMu.Unlock() + + if stopCh != nil { + close(stopCh) + <-doneCh + } +} + +// detach permanently silences all writes to the underlying ResponseWriter and +// stops any active heartbeat goroutine. Used when a durable stream's HTTP +// client disconnects so the detached action goroutine never touches w after +// ServeHTTP returns. +func (s *SSEWriter) detach() { + s.mu.Lock() + s.detached = true + s.mu.Unlock() + s.Close() +} + +func ignoreUnsupported(err error) error { + if errors.Is(err, errors.ErrUnsupported) { + return nil + } + return err +} diff --git a/go/go.work b/go/go.work index 1c9123743a..ca076fb4a2 100644 --- a/go/go.work +++ b/go/go.work @@ -14,7 +14,6 @@ use ( ./plugins/ollama ./plugins/otelgenai ./plugins/postgresql - ./plugins/server ./plugins/systemone ./plugins/vertexai ) diff --git a/go/internal/wire/wire.go b/go/internal/wire/wire.go index 8b2d2107e6..f354b02711 100644 --- a/go/internal/wire/wire.go +++ b/go/internal/wire/wire.go @@ -15,8 +15,8 @@ // SPDX-License-Identifier: Apache-2.0 // Package wire holds the HTTP wire format that the action handler (package -// genkit) serves and the remote agent client (package ai/exp) speaks, so the -// two sides share one definition and cannot drift apart. +// genkithttp) serves and the remote agent client (package ai/exp) speaks, so +// the two sides share one definition and cannot drift apart. // // A request is a POST whose body is a [Request]. A non-streaming response is a // [ResultResponse] on success and an [Error] on failure, with the HTTP status @@ -31,6 +31,7 @@ import ( "github.com/genkit-ai/genkit-go/v2/core/api" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/internal/base" ) // Request is the body of a POST to an action. @@ -108,3 +109,31 @@ func ServesAction(ctx context.Context, key string) bool { k, _ := ctx.Value(servedActionKey{}).(string) return k != "" && k == key } + +// CheckInitSupported rejects an init payload aimed at an action that cannot +// accept one: it returns INVALID_ARGUMENT when init carries a value and the +// action is not bidi, and nil otherwise. Transports call it before committing +// to a response shape (e.g. before writing SSE headers) so the rejection +// surfaces as a proper request error on every path. +func CheckInitSupported(a api.Action, init json.RawMessage) error { + if base.HasJSONValue(init) { + if _, ok := a.(api.BidiAction); !ok { + return status.PublicErrorf(status.ErrInvalidArgument, "action %q does not accept init", a.Name()) + } + } + return nil +} + +// RunActionWithOptionalInit runs an action through its JSON surface, +// dispatching to the bidi one-shot path when init carries a value. Init on a +// non-bidi action is rejected with INVALID_ARGUMENT. Shared by the reflection +// servers and genkithttp so the init-acceptance contract stays in one place. +func RunActionWithOptionalInit(ctx context.Context, a api.Action, input, init json.RawMessage, cb func(context.Context, json.RawMessage) error) (api.RunResult, error) { + if err := CheckInitSupported(a, init); err != nil { + return api.RunResult{}, err + } + if bidi, ok := a.(api.BidiAction); ok && base.HasJSONValue(init) { + return bidi.RunBidiJSON(ctx, input, cb, &api.BidiJSONOptions{Init: init}) + } + return a.RunJSON(ctx, input, cb) +} diff --git a/go/middleware/exp/agents_async_test.go b/go/middleware/exp/agents_async_test.go index 9388f6c129..584eb01f82 100644 --- a/go/middleware/exp/agents_async_test.go +++ b/go/middleware/exp/agents_async_test.go @@ -516,9 +516,9 @@ func answerAgent(text string) aix.AgentFunc[any] { // the task handle, and the wait all cross the wire. func TestAgentsBackgroundDelegationToRemoteAgent(t *testing.T) { server := newTestGenkit(t) - genkitx.DefineCustomAgent(server, "researcher", answerAgent("research complete"), + researcher := genkitx.DefineCustomAgent(server, "researcher", answerAgent("research complete"), aix.WithSessionStore[any](localstore.NewInMemorySessionStore[any]())) - base := serveAgents(t, server) + base := serveAgents(t, researcher) g := newTestGenkit(t) genkitx.DefineRemoteAgent(g, "researcher", base+"/agents/researcher", @@ -570,8 +570,8 @@ func TestAgentsBackgroundDelegationToRemoteAgent(t *testing.T) { // the launch first. func TestAgentsRemoteDetachRefusalRefundsSlot(t *testing.T) { server := newTestGenkit(t) - genkitx.DefineCustomAgent(server, "helper", answerAgent("helped")) // no store: cannot detach - base := serveAgents(t, server) + helper := genkitx.DefineCustomAgent(server, "helper", answerAgent("helped")) // no store: cannot detach + base := serveAgents(t, helper) g := newTestGenkit(t) genkitx.DefineRemoteAgent(g, "helper", base+"/agents/helper") diff --git a/go/middleware/exp/helpers_test.go b/go/middleware/exp/helpers_test.go index ede4cdab66..320800e718 100644 --- a/go/middleware/exp/helpers_test.go +++ b/go/middleware/exp/helpers_test.go @@ -18,13 +18,14 @@ package exp import ( "context" - "net/http" "net/http/httptest" "testing" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" - genkitx "github.com/genkit-ai/genkit-go/v2/exp" + aix "github.com/genkit-ai/genkit-go/v2/ai/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" ) var ctx = context.Background() @@ -45,14 +46,14 @@ func findSystem(msgs []*ai.Message) *ai.Message { return nil } -// serveAgents serves every agent registered with g over HTTP with the -// AllAgentRoutes layout and returns the server's base URL, so a test can -// reach those agents from another Genkit instance as remote agents. -func serveAgents(t *testing.T, g *genkit.Genkit) string { +// serveAgents mounts agents under /agents and returns the server's base URL, +// so a test can reach those agents from another Genkit instance as remote +// agents. +func serveAgents[S any](t *testing.T, agents ...*aix.Agent[S]) string { t.Helper() - mux := http.NewServeMux() - for _, r := range genkitx.AllAgentRoutes(g) { - mux.HandleFunc(r.Pattern(), r.Handler()) + mux := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) + for _, a := range agents { + genkithttpx.HandleAgent(mux, a) } srv := httptest.NewServer(mux) t.Cleanup(srv.Close) diff --git a/go/plugins/firebase/auth.go b/go/plugins/firebase/auth.go index 648b8077f4..d333ff050a 100644 --- a/go/plugins/firebase/auth.go +++ b/go/plugins/firebase/auth.go @@ -18,29 +18,40 @@ package firebase import ( "context" - "encoding/json" + "net/http" "strings" "firebase.google.com/go/v4/auth" genkit "github.com/genkit-ai/genkit-go/v2" - "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) -// AuthContext is the context of an authenticated request. +// AuthContext is the verified Firebase ID token of an authenticated request. type AuthContext = *auth.Token -// AuthPolicy is a function that validates an incoming request. -type AuthPolicy = func(context.Context, AuthContext, json.RawMessage) error +// AuthKey is the typed context key under which [AuthMiddleware] stores the +// verified Firebase ID token. Because it is registered under the name "auth", +// [AuthKey.FromContext] also reads auth payloads supplied via Dev UI / CLI +// --context JSON. +var AuthKey = genkit.NewContextKey[AuthContext]("auth") + +// AuthPolicy validates an authenticated request. Returning a non-nil error +// rejects the request; use [status.PublicErrorf] to control the client-visible +// status and message. +type AuthPolicy = func(ctx context.Context, token AuthContext, r *http.Request) error // AuthClient is a client for the Firebase Auth service. type AuthClient interface { VerifyIDToken(context.Context, string) (*auth.Token, error) } -// ContextProvider creates a Firebase context provider for Genkit actions. -func ContextProvider(ctx context.Context, g *genkit.Genkit, policy AuthPolicy) (core.ContextProvider, error) { +// AuthMiddleware returns standard [net/http] middleware that verifies the +// Firebase ID token in the Authorization Bearer header, runs policy (if +// non-nil), and attaches the verified token to the request context under +// [AuthKey]. Rejections are written with [genkithttp.WriteError]. +func AuthMiddleware(ctx context.Context, g *genkit.Genkit, policy AuthPolicy) (func(http.Handler) http.Handler, error) { f, err := resolvePlugin(g) if err != nil { return nil, err @@ -49,36 +60,43 @@ func ContextProvider(ctx context.Context, g *genkit.Genkit, policy AuthPolicy) ( if err != nil { return nil, err } + return authMiddleware(client, policy), nil +} - return func(ctx context.Context, input core.RequestData) (core.ActionContext, error) { - authHeader, ok := input.Headers["authorization"] - if !ok { - return nil, status.PublicErrorf(status.ErrUnauthenticated, "authorization header is required but not provided") - } - - const bearerPrefix = "bearer " +func authMiddleware(client AuthClient, policy AuthPolicy) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "authorization header is required but not provided")) + return + } - if !strings.HasPrefix(strings.ToLower(authHeader), bearerPrefix) { - return nil, status.PublicErrorf(status.ErrUnauthenticated, "invalid authorization header format") - } + const bearerPrefix = "bearer " + if !strings.HasPrefix(strings.ToLower(authHeader), bearerPrefix) { + genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "invalid authorization header format")) + return + } - token := authHeader[len(bearerPrefix):] - authCtx, err := client.VerifyIDToken(ctx, token) - if err != nil { - // Not public: the Admin SDK's text can name the project (an audience - // claim mismatch quotes the expected project ID). The caller gets - // UNAUTHENTICATED; the detail goes to the log and to GENKIT_ENV=dev. - return nil, status.Errorf(status.ErrUnauthenticated, "error verifying ID token: %w", err) - } + tokenStr := authHeader[len(bearerPrefix):] + token, err := client.VerifyIDToken(r.Context(), tokenStr) + if err != nil { + // Not public: the Admin SDK's text can name the project (an audience + // claim mismatch quotes the expected project ID). The caller gets + // UNAUTHENTICATED; the detail stays server-side outside GENKIT_ENV=dev. + genkithttp.WriteError(w, status.Errorf(status.ErrUnauthenticated, "error verifying ID token: %w", err)) + return + } - if policy != nil { - if err := policy(ctx, authCtx, input.Input); err != nil { - return nil, err + if policy != nil { + if err := policy(r.Context(), token, r); err != nil { + genkithttp.WriteError(w, err) + return + } } - } - return core.ActionContext{ - "auth": authCtx, - }, nil - }, nil + ctx := AuthKey.WithValue(r.Context(), token) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } } diff --git a/go/plugins/firebase/auth_test.go b/go/plugins/firebase/auth_test.go new file mode 100644 index 0000000000..d3aedbbd41 --- /dev/null +++ b/go/plugins/firebase/auth_test.go @@ -0,0 +1,141 @@ +// Copyright 2026 Google LLC +// +// 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. +// +// SPDX-License-Identifier: Apache-2.0 + +package firebase + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "firebase.google.com/go/v4/auth" + + "github.com/genkit-ai/genkit-go/v2/core/status" +) + +type fakeAuthClient struct { + token *auth.Token + err error +} + +func (f fakeAuthClient) VerifyIDToken(_ context.Context, _ string) (*auth.Token, error) { + return f.token, f.err +} + +func TestAuthMiddleware(t *testing.T) { + t.Run("missing header returns 401", func(t *testing.T) { + mw := authMiddleware(fakeAuthClient{}, nil) + h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("next handler should not be called") + })) + + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/flow", nil)) + if w.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want %d", w.Code, http.StatusUnauthorized) + } + if !strings.Contains(w.Body.String(), "UNAUTHENTICATED") { + t.Errorf("body = %q, want UNAUTHENTICATED", w.Body.String()) + } + }) + + t.Run("invalid prefix returns 401", func(t *testing.T) { + mw := authMiddleware(fakeAuthClient{}, nil) + h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("next handler should not be called") + })) + + req := httptest.NewRequest(http.MethodPost, "/flow", nil) + req.Header.Set("Authorization", "Basic abc") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want %d", w.Code, http.StatusUnauthorized) + } + }) + + t.Run("verify failure redacts internal details in prod", func(t *testing.T) { + t.Setenv("GENKIT_ENV", "prod") + mw := authMiddleware(fakeAuthClient{err: errors.New("expected project acme-secret-123")}, nil) + h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("next handler should not be called") + })) + + req := httptest.NewRequest(http.MethodPost, "/flow", nil) + req.Header.Set("Authorization", "Bearer bad-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want %d", w.Code, http.StatusUnauthorized) + } + if strings.Contains(w.Body.String(), "acme-secret-123") { + t.Errorf("response leaked project ID: %q", w.Body.String()) + } + }) + + t.Run("valid token attaches AuthKey and enforces policy", func(t *testing.T) { + want := &auth.Token{UID: "user-42"} + var gotUID string + mw := authMiddleware(fakeAuthClient{token: want}, func(ctx context.Context, tok AuthContext, r *http.Request) error { + if tok.UID != "user-42" { + return status.PublicErrorf(status.ErrPermissionDenied, "wrong user") + } + return nil + }) + h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tok, ok := AuthKey.FromContext(r.Context()) + if !ok { + t.Fatal("AuthKey not present in context") + } + gotUID = tok.UID + w.WriteHeader(http.StatusOK) + })) + + req := httptest.NewRequest(http.MethodPost, "/flow", nil) + req.Header.Set("Authorization", "Bearer good-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Errorf("status = %d, want %d", w.Code, http.StatusOK) + } + if gotUID != "user-42" { + t.Errorf("UID = %q, want %q", gotUID, "user-42") + } + }) + + t.Run("policy rejection returns mapped status", func(t *testing.T) { + mw := authMiddleware(fakeAuthClient{token: &auth.Token{UID: "u"}}, func(ctx context.Context, tok AuthContext, r *http.Request) error { + return status.PublicErrorf(status.ErrPermissionDenied, "email not verified") + }) + h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("next handler should not be called") + })) + + req := httptest.NewRequest(http.MethodPost, "/flow", nil) + req.Header.Set("Authorization", "Bearer good-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusForbidden { + t.Errorf("status = %d, want %d", w.Code, http.StatusForbidden) + } + if !strings.Contains(w.Body.String(), "email not verified") { + t.Errorf("body = %q, want public message", w.Body.String()) + } + }) +} diff --git a/go/plugins/server/go.mod b/go/plugins/server/go.mod deleted file mode 100644 index d7c33c435c..0000000000 --- a/go/plugins/server/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/genkit-ai/genkit-go/plugins/server - -go 1.25.0 diff --git a/go/plugins/server/server.go b/go/plugins/server/server.go deleted file mode 100644 index 9e880fe5aa..0000000000 --- a/go/plugins/server/server.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2025 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package server - -import ( - "context" - "errors" - "fmt" - "log/slog" - "net/http" - "os" - "os/signal" - "syscall" - "time" -) - -// shutdownTimeout bounds the graceful drain of in-flight requests after an -// interrupt, matching the reflection server's shutdown timeout. -const shutdownTimeout = 5 * time.Second - -// Start starts a new HTTP server and manages its lifecycle. -// This is a convenience function since Go does not manage interrupt signals directly. -// It returns nil after a graceful shutdown on SIGINT or SIGTERM. -func Start(ctx context.Context, addr string, mux *http.ServeMux) error { - ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) - defer cancel() - - srv := &http.Server{ - Addr: addr, - Handler: mux, - } - - errChan := make(chan error, 1) - - go func() { - slog.Info("server listening", "addr", addr) - if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - errChan <- fmt.Errorf("server error: %w", err) - } - cancel() - }() - - select { - case err := <-errChan: - return err - case <-ctx.Done(): - slog.Info("server shutting down", "addr", addr) - // Stop intercepting signals so a second interrupt kills the process - // immediately instead of being swallowed while requests drain. - cancel() - // ctx is already canceled here; Shutdown needs a fresh context or it - // returns immediately without draining in-flight requests. - shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), shutdownTimeout) - defer cancelShutdown() - if err := srv.Shutdown(shutdownCtx); err != nil { - return fmt.Errorf("failed to shutdown server: %w", err) - } - } - return nil -} diff --git a/go/reflection.go b/go/reflection.go index 5135f766d9..8573d96916 100644 --- a/go/reflection.go +++ b/go/reflection.go @@ -42,6 +42,7 @@ import ( "github.com/genkit-ai/genkit-go/v2/internal" "github.com/genkit-ai/genkit-go/v2/internal/base" "github.com/genkit-ai/genkit-go/v2/internal/tracingbridge" + "github.com/genkit-ai/genkit-go/v2/internal/wire" ) type streamingCallback[Stream any] = func(context.Context, Stream) error @@ -844,7 +845,7 @@ func runAction(ctx context.Context, g *Genkit, key string, input, init json.RawM ctx = tracing.WithTelemetryLabels(ctx, telemetryAttributes) } - res, err := runActionWithOptionalInit(ctx, action, input, init, cb) + res, err := wire.RunActionWithOptionalInit(ctx, action, input, init, cb) if err != nil { return &runActionResponse{Telemetry: telemetry{TraceID: res.TraceID}}, err } @@ -854,33 +855,16 @@ func runAction(ctx context.Context, g *Genkit, key string, input, init json.RawM }, nil } -// checkInitSupported rejects an init payload aimed at an action that cannot -// accept one: it returns INVALID_ARGUMENT when init carries a value and the -// action is not bidi, and nil otherwise. Transports call it before committing -// to a response shape (e.g. before writing SSE headers) so the rejection -// surfaces as a proper request error on every path. -func checkInitSupported(a api.Action, init json.RawMessage) error { - if base.HasJSONValue(init) { - if _, ok := a.(api.BidiAction); !ok { - return status.PublicErrorf(status.ErrInvalidArgument, "action %q does not accept init", a.Name()) +func parseBoolQueryParam(r *http.Request, name string) (bool, error) { + b := false + if s := r.URL.Query().Get(name); s != "" { + var err error + b, err = strconv.ParseBool(s) + if err != nil { + return false, status.PublicErrorf(status.ErrInvalidArgument, "%w", err) } } - return nil -} - -// runActionWithOptionalInit runs an action through its JSON surface, -// dispatching to the bidi one-shot path when init carries a value. Init on a -// non-bidi action is rejected with INVALID_ARGUMENT. Shared by the reflection -// servers and the HTTP action handler so the init-acceptance contract stays -// in one place. -func runActionWithOptionalInit(ctx context.Context, a api.Action, input, init json.RawMessage, cb streamingCallback[json.RawMessage]) (api.RunResult, error) { - if err := checkInitSupported(a, init); err != nil { - return api.RunResult{}, err - } - if bidi, ok := a.(api.BidiAction); ok && base.HasJSONValue(init) { - return bidi.RunBidiJSON(ctx, input, cb, &api.BidiJSONOptions{Init: init}) - } - return a.RunJSON(ctx, input, cb) + return b, nil } // writeJSON writes a JSON-marshaled value to the response writer. diff --git a/go/reflection_v2.go b/go/reflection_v2.go index 4e05441d4b..e844086d8d 100644 --- a/go/reflection_v2.go +++ b/go/reflection_v2.go @@ -834,7 +834,7 @@ func (s *reflectionServerV2) sendRunActionError(id string, err error, traceID st // The reflection API serves the Dev UI, so it reports the real message and // stack. Suppressing them here would only hide the failure from the // developer causing it; the redaction that matters is at the flow HTTP - // boundary (see clientError in server.go). + // boundary (see genkithttp.WriteError). e := status.Convert(err) if e == nil { // err was a non-nil interface holding a nil *status.Error, which diff --git a/go/samples/anthropic/main.go b/go/samples/anthropic/main.go index 7def0c57e9..3fd82c0dc4 100644 --- a/go/samples/anthropic/main.go +++ b/go/samples/anthropic/main.go @@ -45,13 +45,12 @@ import ( "context" "fmt" "log" - "net/http" sdk "github.com/anthropics/anthropic-sdk-go" "github.com/genkit-ai/genkit-go/plugins/anthropic" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -104,11 +103,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-agents-remote/main.go b/go/samples/basic-agents-remote/main.go index c45f54d6f9..bbf2033920 100644 --- a/go/samples/basic-agents-remote/main.go +++ b/go/samples/basic-agents-remote/main.go @@ -46,17 +46,17 @@ import ( "context" "io" "log" - "net/http" "os" "os/exec" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" aix "github.com/genkit-ai/genkit-go/v2/ai/exp" "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" genkitx "github.com/genkit-ai/genkit-go/v2/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" middlewarex "github.com/genkit-ai/genkit-go/v2/middleware/exp" ) @@ -86,7 +86,7 @@ func main() { }), ) - genkitx.DefineAgent(g, "orchestrator", + orchestrator := genkitx.DefineAgent(g, "orchestrator", aix.InlinePrompt{ ai.WithModelName("googleai/gemini-flash-latest"), ai.WithSystem("You are a planning assistant. When a question has several parts, " + @@ -104,13 +104,10 @@ func main() { aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()), ) - // AllAgentRoutes serves the orchestrator and skips the researcher, which - // is another service's agent. - mux := http.NewServeMux() - for _, route := range genkitx.AllAgentRoutes(g) { - mux.HandleFunc(route.Pattern(), route.Handler()) - } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + // Mount only the orchestrator; the researcher runs on its own service. + mux := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) + genkithttpx.HandleAgent(mux, orchestrator) + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-agents-remote/researcher/main.go b/go/samples/basic-agents-remote/researcher/main.go index 283dd0b4f1..bee51b229f 100644 --- a/go/samples/basic-agents-remote/researcher/main.go +++ b/go/samples/basic-agents-remote/researcher/main.go @@ -26,16 +26,16 @@ import ( "context" "io" "log" - "net/http" "os" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" aix "github.com/genkit-ai/genkit-go/v2/ai/exp" "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" genkitx "github.com/genkit-ai/genkit-go/v2/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" ) func main() { @@ -57,7 +57,7 @@ func main() { // background: a background task is a pending snapshot in this store, which // the caller follows through the getSnapshot, waitForSnapshot, and abort // routes. A deployed service would use a store all its replicas share. - genkitx.DefineAgent(g, "researcher", + researcher := genkitx.DefineAgent(g, "researcher", aix.InlinePrompt{ ai.WithModelName("googleai/gemini-flash-latest"), ai.WithSystem("You are a research assistant. You get one question at a time. " + @@ -66,11 +66,9 @@ func main() { aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()), ) - mux := http.NewServeMux() - for _, route := range genkitx.AllAgentRoutes(g) { - mux.HandleFunc(route.Pattern(), route.Handler()) - } - if err := server.Start(ctx, "127.0.0.1:8081", mux); err != nil { + mux := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) + genkithttpx.HandleAgent(mux, researcher) + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8081", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-agents-server/main.go b/go/samples/basic-agents-server/main.go index 45f679c137..716f2563e2 100644 --- a/go/samples/basic-agents-server/main.go +++ b/go/samples/basic-agents-server/main.go @@ -100,19 +100,19 @@ import ( "flag" "fmt" "log" - "net/http" "os" "github.com/genkit-ai/genkit-go/plugins/googlegenai" "github.com/genkit-ai/genkit-go/plugins/postgresql" pgexp "github.com/genkit-ai/genkit-go/plugins/postgresql/exp" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" aix "github.com/genkit-ai/genkit-go/v2/ai/exp" "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" "github.com/genkit-ai/genkit-go/v2/core/api" genkitx "github.com/genkit-ai/genkit-go/v2/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" "github.com/jackc/pgx/v5/pgxpool" "google.golang.org/genai" ) @@ -159,7 +159,7 @@ func main() { if err != nil { log.Fatalf("creating session store: %v", err) } - genkitx.DefineAgent(g, "chat", + chatAgent := genkitx.DefineAgent(g, "chat", aix.InlinePrompt{ ai.WithModel(model), ai.WithSystem("You are a helpful travel assistant. Keep responses to a couple of sentences."), @@ -170,31 +170,25 @@ func main() { // "statelessChat" keeps no state on the server: each response carries // the full conversation state and the client round-trips it on the next // request. This suits deployments where the server must stay stateless. - genkitx.DefineAgent[any](g, "statelessChat", + statelessChatAgent := genkitx.DefineAgent[any](g, "statelessChat", aix.InlinePrompt{ ai.WithModel(model), ai.WithSystem("You are a helpful travel assistant. Keep responses to a couple of sentences."), }, ) - // AllAgentRoutes lays out a default HTTP surface for every registered - // agent, following each one's capabilities, so the store-backed and - // client-managed agents can be served side by side from one call: + // HandleAgent mounts each agent and its applicable companion routes under + // the Mux base path: // // POST /agents/chat one turn per request // POST /agents/chat/getSnapshot read a snapshot by ID // POST /agents/chat/waitForSnapshot block until a snapshot settles // POST /agents/chat/abort abort background work // POST /agents/statelessChat one turn per request - // - // route.Pattern() is its "METHOD /path" and route.Handler() builds the - // genkit.Handler, so any router works the same way. For a subset use - // genkitx.AgentRoutes(agent), and for flows genkitx.AllFlowRoutes(g). - mux := http.NewServeMux() - for _, route := range genkitx.AllAgentRoutes(g) { - mux.HandleFunc(route.Pattern(), route.Handler()) - } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + apiMux := genkithttp.NewMux(genkithttp.WithBasePath("/agents")) + genkithttpx.HandleAgent(apiMux, chatAgent) + genkithttpx.HandleAgent(apiMux, statelessChatAgent) + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", apiMux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-decisions/main.go b/go/samples/basic-decisions/main.go index a9f85e0c94..0cbdd7ce6a 100644 --- a/go/samples/basic-decisions/main.go +++ b/go/samples/basic-decisions/main.go @@ -91,15 +91,14 @@ import ( "errors" "fmt" "log" - "net/http" "slices" "sync" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" systemonex "github.com/genkit-ai/genkit-go/plugins/systemone/exp" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -342,11 +341,11 @@ func main() { DefineToolPick(g) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-durable-streaming-exp/main.go b/go/samples/basic-durable-streaming-exp/main.go index b83a682029..a89c392045 100644 --- a/go/samples/basic-durable-streaming-exp/main.go +++ b/go/samples/basic-durable-streaming-exp/main.go @@ -60,12 +60,11 @@ import ( "context" "fmt" "log" - "net/http" "time" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/core/x/streaming" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) type ( @@ -122,11 +121,11 @@ func main() { // streams in memory and drops a finished one 10 minutes later, so a // reconnect works for that long and a restart loses them all. Serving the // flow without it leaves the flow itself unchanged and the stream ordinary. - mux := http.NewServeMux() - mux.HandleFunc("POST /countdown", genkit.Handler(countdown, - genkit.WithStreamManager(streaming.NewInMemoryStreamManager(streaming.WithTTL(10*time.Minute))), - )) - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + mux := genkithttp.NewMux() + genkithttp.HandleAction(mux, countdown, + genkithttp.WithStreamManager(streaming.NewInMemoryStreamManager(streaming.WithTTL(10*time.Minute))), + ) + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-errors/main.go b/go/samples/basic-errors/main.go index cf68e58183..942fd01cd7 100644 --- a/go/samples/basic-errors/main.go +++ b/go/samples/basic-errors/main.go @@ -68,16 +68,15 @@ import ( "errors" "fmt" "log" - "net/http" "strings" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/logger" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -227,11 +226,11 @@ func main() { return "", errors.New("connecting to db at 10.0.0.3 as admin: password rejected") }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-flows/main.go b/go/samples/basic-flows/main.go index ca9a1b3769..f217b585f7 100644 --- a/go/samples/basic-flows/main.go +++ b/go/samples/basic-flows/main.go @@ -31,13 +31,12 @@ import ( "errors" "fmt" "log" - "net/http" "strings" "time" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) func main() { @@ -198,10 +197,10 @@ func main() { return fmt.Sprintf("done: %d, streamed: %d times", count, i), nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, flow := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+flow.Name(), genkit.Handler(flow)) + genkithttp.HandleAction(mux, flow) } fmt.Println("Starting server on http://127.0.0.1:8080 ...") - log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) + log.Fatal(genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux)) } diff --git a/go/samples/basic-formats/main.go b/go/samples/basic-formats/main.go index 25cf7267b6..af8d2c91cc 100644 --- a/go/samples/basic-formats/main.go +++ b/go/samples/basic-formats/main.go @@ -52,14 +52,13 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -111,11 +110,11 @@ func main() { DefineRatingWithEnum(g) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-media/main.go b/go/samples/basic-media/main.go index 75ea3c708f..3b8753dadb 100644 --- a/go/samples/basic-media/main.go +++ b/go/samples/basic-media/main.go @@ -64,18 +64,17 @@ import ( "encoding/base64" "fmt" "log" - "net/http" "os" "strings" "time" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/logger" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -207,11 +206,11 @@ func main() { DefineAnimate(g, client) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-middleware/a2ui/main.go b/go/samples/basic-middleware/a2ui/main.go index c80bbe096a..35f18506b0 100644 --- a/go/samples/basic-middleware/a2ui/main.go +++ b/go/samples/basic-middleware/a2ui/main.go @@ -50,17 +50,16 @@ package main import ( "context" "log" - "net/http" a2uix "github.com/genkit-ai/genkit-go/plugins/a2ui/exp" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" aix "github.com/genkit-ai/genkit-go/v2/ai/exp" "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" - "github.com/genkit-ai/genkit-go/v2/core/api" genkitx "github.com/genkit-ai/genkit-go/v2/exp" + "github.com/genkit-ai/genkit-go/v2/genkithttp" + genkithttpx "github.com/genkit-ai/genkit-go/v2/genkithttp/exp" "github.com/genkit-ai/genkit-go/v2/middleware" ) @@ -139,39 +138,15 @@ condition, humidity). Feel free to add a Button (e.g. "Refresh") when useful.`), ) // Serve the agent at /api/uiAgent, the endpoint the web UI's - // remoteAgent({ url: '/api/uiAgent' }) talks to, plus the companion - // endpoints it derives from that base (/getSnapshot and /abort). Each - // handler is wrapped with permissive CORS so the browser can reach it - // (a no-op behind the Vite proxy, but handy for `pnpm dev`). The routes - // also register bare paths (without the POST method prefix) so the CORS - // preflight OPTIONS requests are matched. - mux := http.NewServeMux() - handle := func(path string, a api.Action) { - mux.Handle(path, withCORS(genkit.Handler(a))) - } - handle("/api/uiAgent", uiAgent) - handle("/api/uiAgent/getSnapshot", uiAgent.GetSnapshotAction()) - handle("/api/uiAgent/abort", uiAgent.AbortAction()) + // remoteAgent({ url: '/api/uiAgent' }) talks to, plus its companion + // endpoints (/getSnapshot, /waitForSnapshot, and /abort), wrapped with + // permissive CORS so the browser can reach it during `pnpm dev`. + apiMux := genkithttp.NewMux(genkithttp.WithBasePath("/api")) + genkithttpx.HandleAgent(apiMux, uiAgent) + handler := genkithttp.CORS(genkithttp.CORSOptions{})(apiMux) log.Print("A2UI agent server listening on http://localhost:8080 (POST /api/uiAgent)") - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", handler); err != nil { log.Fatal(err) } } - -// withCORS wraps h with permissive CORS headers so a browser served from a -// different origin (e.g. the Vite dev server on :5173) can call the agent -// directly. When using `pnpm preview`, requests are same-origin via the Vite -// proxy and CORS is a no-op, but this keeps `pnpm dev` working too. -func withCORS(h http.Handler) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, x-genkit-stream-id") - if r.Method == http.MethodOptions { - w.WriteHeader(http.StatusNoContent) - return - } - h.ServeHTTP(w, r) - } -} diff --git a/go/samples/basic-middleware/budget/main.go b/go/samples/basic-middleware/budget/main.go index c6caaa1c44..bb8c90e7cc 100644 --- a/go/samples/basic-middleware/budget/main.go +++ b/go/samples/basic-middleware/budget/main.go @@ -44,12 +44,11 @@ import ( "errors" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" middlewarex "github.com/genkit-ai/genkit-go/v2/middleware/exp" ) @@ -149,9 +148,9 @@ func main() { return resp.Text(), nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux)) + log.Fatal(genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux)) } diff --git a/go/samples/basic-middleware/context-compression/main.go b/go/samples/basic-middleware/context-compression/main.go index 0e3c164903..b7a38a3633 100644 --- a/go/samples/basic-middleware/context-compression/main.go +++ b/go/samples/basic-middleware/context-compression/main.go @@ -47,13 +47,12 @@ import ( "context" "fmt" "log" - "net/http" "strings" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/genkit-ai/genkit-go/v2/middleware" middlewarex "github.com/genkit-ai/genkit-go/v2/middleware/exp" ) @@ -178,11 +177,11 @@ func main() { return result, nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-middleware/filesystem/main.go b/go/samples/basic-middleware/filesystem/main.go index 2821ae1c63..e468c84902 100644 --- a/go/samples/basic-middleware/filesystem/main.go +++ b/go/samples/basic-middleware/filesystem/main.go @@ -46,13 +46,12 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/genkit-ai/genkit-go/v2/middleware" "google.golang.org/genai" ) @@ -96,11 +95,11 @@ func main() { DefineExploreFlow(g) DefineEditFlow(g) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-middleware/metering/main.go b/go/samples/basic-middleware/metering/main.go index 2dda97108c..4311fdc3f1 100644 --- a/go/samples/basic-middleware/metering/main.go +++ b/go/samples/basic-middleware/metering/main.go @@ -46,15 +46,14 @@ import ( "context" "fmt" "log" - "net/http" "sync" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" aix "github.com/genkit-ai/genkit-go/v2/ai/exp" "github.com/genkit-ai/genkit-go/v2/core/tracing" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // QuestionRequest is what answerFlow takes. The fields carry descriptions and @@ -137,11 +136,11 @@ func main() { return meter.Tokens(tenant), nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-middleware/retry-fallback/main.go b/go/samples/basic-middleware/retry-fallback/main.go index 715dbc3b2f..79829141e7 100644 --- a/go/samples/basic-middleware/retry-fallback/main.go +++ b/go/samples/basic-middleware/retry-fallback/main.go @@ -49,13 +49,12 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/genkit-ai/genkit-go/v2/middleware" "google.golang.org/genai" ) @@ -111,11 +110,11 @@ func main() { return text, nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-middleware/skills/main.go b/go/samples/basic-middleware/skills/main.go index 6b6b68e64f..ea6200185d 100644 --- a/go/samples/basic-middleware/skills/main.go +++ b/go/samples/basic-middleware/skills/main.go @@ -55,13 +55,12 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/genkit-ai/genkit-go/v2/middleware" "google.golang.org/genai" ) @@ -96,11 +95,11 @@ func main() { DefineAskFlow(g) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-prompt-content/main.go b/go/samples/basic-prompt-content/main.go index 600abe7133..2bc0aa9cd7 100644 --- a/go/samples/basic-prompt-content/main.go +++ b/go/samples/basic-prompt-content/main.go @@ -50,14 +50,13 @@ import ( "context" "fmt" "log" - "net/http" "strings" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -135,11 +134,11 @@ func main() { DefineTriage(g) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-prompts/main.go b/go/samples/basic-prompts/main.go index bdb78e0594..ea04e0bb66 100644 --- a/go/samples/basic-prompts/main.go +++ b/go/samples/basic-prompts/main.go @@ -54,15 +54,14 @@ import ( "embed" "fmt" "log" - "net/http" "strings" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/genkit-ai/genkit-go/v2/middleware" "google.golang.org/genai" ) @@ -180,11 +179,11 @@ func main() { DefineChatWithDotprompt(g) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-structured/main.go b/go/samples/basic-structured/main.go index 968d71420d..6d8194e5f6 100644 --- a/go/samples/basic-structured/main.go +++ b/go/samples/basic-structured/main.go @@ -47,14 +47,13 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -115,11 +114,11 @@ func main() { DefineRecipe(g) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-tool-interrupts/main.go b/go/samples/basic-tool-interrupts/main.go index 1e3f5f21d0..8e1cf4d11a 100644 --- a/go/samples/basic-tool-interrupts/main.go +++ b/go/samples/basic-tool-interrupts/main.go @@ -75,16 +75,15 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/ai/tool" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/logger" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -253,11 +252,11 @@ func main() { }) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic-tools/main.go b/go/samples/basic-tools/main.go index d3e7a5f252..8217b742a7 100644 --- a/go/samples/basic-tools/main.go +++ b/go/samples/basic-tools/main.go @@ -59,18 +59,17 @@ import ( "image/draw" "image/png" "log" - "net/http" "slices" "strings" "time" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" "github.com/genkit-ai/genkit-go/v2/ai/tool" "github.com/genkit-ai/genkit-go/v2/core" "github.com/genkit-ai/genkit-go/v2/core/status" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -209,11 +208,11 @@ func main() { }) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/basic/main.go b/go/samples/basic/main.go index 903afae7eb..95760f43b3 100644 --- a/go/samples/basic/main.go +++ b/go/samples/basic/main.go @@ -42,12 +42,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -103,11 +102,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/anthropic/main.go b/go/samples/compat_oai/anthropic/main.go index 4a9cca8798..b1a90ad08b 100644 --- a/go/samples/compat_oai/anthropic/main.go +++ b/go/samples/compat_oai/anthropic/main.go @@ -43,12 +43,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/anthropic" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -95,11 +94,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/custom/main.go b/go/samples/compat_oai/custom/main.go index 82ebeb0f18..fe8fc5ecbc 100644 --- a/go/samples/compat_oai/custom/main.go +++ b/go/samples/compat_oai/custom/main.go @@ -45,13 +45,12 @@ import ( "context" "fmt" "log" - "net/http" "os" "github.com/genkit-ai/genkit-go/plugins/compat_oai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/openai/openai-go" ) @@ -113,11 +112,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/dashscope/main.go b/go/samples/compat_oai/dashscope/main.go index 6500ca3f81..cca3a261aa 100644 --- a/go/samples/compat_oai/dashscope/main.go +++ b/go/samples/compat_oai/dashscope/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/dashscope" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/openai/openai-go" ) @@ -90,11 +89,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/deepseek/main.go b/go/samples/compat_oai/deepseek/main.go index f1e89e7159..3ff5113290 100644 --- a/go/samples/compat_oai/deepseek/main.go +++ b/go/samples/compat_oai/deepseek/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/deepseek" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -88,11 +87,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/kimi/main.go b/go/samples/compat_oai/kimi/main.go index 7801e3d317..3551b6b111 100644 --- a/go/samples/compat_oai/kimi/main.go +++ b/go/samples/compat_oai/kimi/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/kimi" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -89,11 +88,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/mistral/main.go b/go/samples/compat_oai/mistral/main.go index 64a7b6a4b1..396f4931d2 100644 --- a/go/samples/compat_oai/mistral/main.go +++ b/go/samples/compat_oai/mistral/main.go @@ -42,12 +42,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/mistral" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the jokes flow takes. A struct rather than a bare @@ -117,11 +116,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/openai/main.go b/go/samples/compat_oai/openai/main.go index ed6c108e8e..c9661b7c90 100644 --- a/go/samples/compat_oai/openai/main.go +++ b/go/samples/compat_oai/openai/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" oai "github.com/genkit-ai/genkit-go/plugins/compat_oai/openai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "github.com/openai/openai-go" ) @@ -90,11 +89,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/openrouter/main.go b/go/samples/compat_oai/openrouter/main.go index 85261047ad..5409657479 100644 --- a/go/samples/compat_oai/openrouter/main.go +++ b/go/samples/compat_oai/openrouter/main.go @@ -39,12 +39,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/openrouter" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -101,11 +100,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/xai/main.go b/go/samples/compat_oai/xai/main.go index 5d915f8a54..ba35738ebf 100644 --- a/go/samples/compat_oai/xai/main.go +++ b/go/samples/compat_oai/xai/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/xai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -88,11 +87,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/compat_oai/zai/main.go b/go/samples/compat_oai/zai/main.go index 073a62ca0e..34dfd59b83 100644 --- a/go/samples/compat_oai/zai/main.go +++ b/go/samples/compat_oai/zai/main.go @@ -38,12 +38,11 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/compat_oai/zai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) // JokeRequest is what the flow takes. A struct rather than a bare string lets @@ -88,11 +87,11 @@ func main() { ) // Serve every flow over HTTP. - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } - if err := server.Start(ctx, "127.0.0.1:8080", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8080", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/durable-streaming-firestore/main.go b/go/samples/durable-streaming-firestore/main.go index 228f9797fe..f0b63940cd 100644 --- a/go/samples/durable-streaming-firestore/main.go +++ b/go/samples/durable-streaming-firestore/main.go @@ -45,13 +45,12 @@ import ( "context" "fmt" "log" - "net/http" "time" "github.com/genkit-ai/genkit-go/plugins/firebase" firebasex "github.com/genkit-ai/genkit-go/plugins/firebase/exp" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) func main() { @@ -106,9 +105,9 @@ func main() { // Set up HTTP server with durable streaming enabled. // Completed streams are kept for 10 minutes before cleanup. - mux := http.NewServeMux() - mux.HandleFunc("POST /countdown", genkit.Handler(countdown, genkit.WithStreamManager(sm))) - if err := server.Start(ctx, "127.0.0.1:8088", mux); err != nil { + mux := genkithttp.NewMux() + genkithttp.HandleAction(mux, countdown, genkithttp.WithStreamManager(sm)) + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:8088", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/go.mod b/go/samples/go.mod index 6a1e5d31d6..10abf2855d 100644 --- a/go/samples/go.mod +++ b/go/samples/go.mod @@ -13,7 +13,6 @@ require ( github.com/genkit-ai/genkit-go/plugins/ollama v0.0.0-00010101000000-000000000000 github.com/genkit-ai/genkit-go/plugins/otelgenai v0.0.0-00010101000000-000000000000 github.com/genkit-ai/genkit-go/plugins/postgresql v0.0.0-00010101000000-000000000000 - github.com/genkit-ai/genkit-go/plugins/server v0.0.0-00010101000000-000000000000 github.com/genkit-ai/genkit-go/plugins/systemone v0.0.0-00010101000000-000000000000 github.com/genkit-ai/genkit-go/plugins/vertexai v0.0.0-00010101000000-000000000000 github.com/genkit-ai/genkit-go/v2 v2.0.0-00010101000000-000000000000 @@ -158,8 +157,6 @@ replace github.com/genkit-ai/genkit-go/plugins/otelgenai => ../plugins/otelgenai replace github.com/genkit-ai/genkit-go/plugins/postgresql => ../plugins/postgresql -replace github.com/genkit-ai/genkit-go/plugins/server => ../plugins/server - replace github.com/genkit-ai/genkit-go/plugins/systemone => ../plugins/systemone replace github.com/genkit-ai/genkit-go/plugins/vertexai => ../plugins/vertexai diff --git a/go/samples/telemetry-test/kitchen_sink/kitchen_sink.go b/go/samples/telemetry-test/kitchen_sink/kitchen_sink.go index b142adbdd1..dd5169b1be 100644 --- a/go/samples/telemetry-test/kitchen_sink/kitchen_sink.go +++ b/go/samples/telemetry-test/kitchen_sink/kitchen_sink.go @@ -18,13 +18,12 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/firebase" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -154,14 +153,14 @@ func main() { fmt.Println("Batch Processing:") fmt.Println(`curl -X POST http://localhost:3400/batchFlow -H 'Content-Type: application/json' -d '{"data": ["AI", "robotics", "quantum"]}'`) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, flow := range genkit.ListFlows(g) { fmt.Printf("Registered flow: %s\n", flow.Name()) - mux.HandleFunc("POST /"+flow.Name(), genkit.Handler(flow)) + genkithttp.HandleAction(mux, flow) } fmt.Println("\nAll telemetry modules active - check Google Cloud Console!") - if err := server.Start(ctx, "127.0.0.1:3400", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:3400", mux); err != nil { log.Fatal(err) } } diff --git a/go/samples/telemetry-test/simple/simple_joke.go b/go/samples/telemetry-test/simple/simple_joke.go index b213a2dd12..1713134e57 100644 --- a/go/samples/telemetry-test/simple/simple_joke.go +++ b/go/samples/telemetry-test/simple/simple_joke.go @@ -18,13 +18,12 @@ import ( "context" "fmt" "log" - "net/http" "github.com/genkit-ai/genkit-go/plugins/firebase" "github.com/genkit-ai/genkit-go/plugins/googlegenai" - "github.com/genkit-ai/genkit-go/plugins/server" genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" "google.golang.org/genai" ) @@ -67,14 +66,14 @@ func main() { fmt.Println("Test with:") fmt.Println(`curl -X POST http://localhost:3400/jokeFlow -H 'Content-Type: application/json' -d '{"data": "cats"}'`) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, flow := range genkit.ListFlows(g) { fmt.Printf("Registered flow: %s\n", flow.Name()) - mux.HandleFunc("POST /"+flow.Name(), genkit.Handler(flow)) + genkithttp.HandleAction(mux, flow) } fmt.Println("\nStarting server on http://127.0.0.1:3400...") - if err := server.Start(ctx, "127.0.0.1:3400", mux); err != nil { + if err := genkithttp.ListenAndServe(ctx, "127.0.0.1:3400", mux); err != nil { log.Fatalf("Failed to start server: %v", err) } } diff --git a/go/server.go b/go/server.go deleted file mode 100644 index 3c94674805..0000000000 --- a/go/server.go +++ /dev/null @@ -1,537 +0,0 @@ -// Copyright 2025 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package genkit - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "log/slog" - "maps" - "net/http" - "strconv" - "strings" - "sync/atomic" - "time" - - "github.com/google/uuid" - - "github.com/genkit-ai/genkit-go/v2/core" - "github.com/genkit-ai/genkit-go/v2/core/api" - "github.com/genkit-ai/genkit-go/v2/core/logger" - "github.com/genkit-ai/genkit-go/v2/core/status" - "github.com/genkit-ai/genkit-go/v2/core/x/streaming" - "github.com/genkit-ai/genkit-go/v2/internal/wire" -) - -// HandlerOption configures a Handler. -type HandlerOption interface { - applyHandler(*handlerOptions) error -} - -// handlerOptions are options for an action HTTP handler. -type handlerOptions struct { - ContextProviders []core.ContextProvider // Providers for action context that may be used during runtime. - StreamManager streaming.StreamManager // Optional manager for durable stream storage. -} - -func (o *handlerOptions) applyHandler(opts *handlerOptions) error { - // Context providers accumulate, as plugins do. - opts.ContextProviders = append(opts.ContextProviders, o.ContextProviders...) - - if o.StreamManager != nil { - if opts.StreamManager != nil { - return errors.New("cannot set StreamManager more than once (WithStreamManager)") - } - opts.StreamManager = o.StreamManager - } - - return nil -} - -// requestID is a unique ID for each request. -var requestID atomic.Int64 - -// WithContextProviders adds providers for action context that may be used during runtime. -// They are called in the order added and may overwrite previous context. -func WithContextProviders(ctxProviders ...core.ContextProvider) HandlerOption { - return &handlerOptions{ContextProviders: ctxProviders} -} - -// WithStreamManager enables durable streaming with the provided StreamManager. -// When enabled, streaming responses include an x-genkit-stream-id header that clients -// can use to reconnect to in-progress or completed streams. -// -// EXPERIMENTAL: This API is subject to change. -func WithStreamManager(manager streaming.StreamManager) HandlerOption { - return &handlerOptions{StreamManager: manager} -} - -// Handler returns an HTTP handler function that serves the action with the provided options. -// -// The provided HandlerOptions are applied during construction. If any option -// fails to apply, Handler panics. -// -// A failure is sent as a JSON {"status", "message"} body. Outside the dev -// environment, an error not made with [status.PublicErrorf] goes out with the -// generic message for its status, so internal text stays in the server log. -// An agent served by Handler gets the same treatment for the errors in its -// outputs and snapshots; an agent run any other way, such as from a handler of -// your own that calls it, returns them unchanged. -// -// Example: -// -// genkit.Handler( -// myFlow, -// genkit.WithContextProviders(func(ctx context.Context, req core.RequestData) (core.ActionContext, error) { -// return core.ActionContext{"uid": req.Headers["authorization"]}, nil -// })) -func Handler(a api.Action, opts ...HandlerOption) http.HandlerFunc { - return wrapHandler(HandlerFunc(a, opts...)) -} - -// HandlerFunc returns an HTTP handler function that executes the given action -// and returns an error instead of writing it directly to the response. -// -// It is intended for use with web frameworks that expect handlers with the -// signature: -// -// func(http.ResponseWriter, *http.Request) error -// -// so that errors can be handled centrally (e.g., by middleware). -// -// The provided HandlerOptions are applied during construction. If any option -// fails to apply, HandlerFunc panics. -// -// Example: -// -// genkit.HandlerFunc( -// myFlow, -// genkit.WithContextProviders(func(ctx context.Context, req core.RequestData) (core.ActionContext, error) { -// return core.ActionContext{"uid": req.Headers["authorization"]}, nil -// }), -// ) -func HandlerFunc(a api.Action, opts ...HandlerOption) func(http.ResponseWriter, *http.Request) error { - options := &handlerOptions{} - for _, opt := range opts { - if err := opt.applyHandler(options); err != nil { - panic(fmt.Errorf("genkit.HandlerFunc: error applying options: %w", err)) - } - } - - return handler(a, options) -} - -// wrapHandler wraps an HTTP handler function with common logging and error handling. -func wrapHandler(h func(http.ResponseWriter, *http.Request) error) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - log := slog.Default().With("reqId", requestID.Add(1)) - // Carry the request-scoped logger in the context so everything logged - // while handling this request (including inside flows and tools) is - // tagged with the same reqId. - r = r.WithContext(logger.WithContext(r.Context(), log)) - ctx := r.Context() - - start := time.Now() - logger.Debug(ctx, "request started", "method", r.Method, "path", r.URL.Path) - - var err error - defer func() { - if clientDisconnected(ctx, err) { - logger.Debug(ctx, "client disconnected", - "method", r.Method, - "path", r.URL.Path, - "duration", time.Since(start).Round(time.Millisecond), - "error", err) - } else if err != nil { - logger.Error(ctx, "request failed", - "method", r.Method, - "path", r.URL.Path, - "duration", time.Since(start).Round(time.Millisecond), - "error", err) - } else { - logger.Debug(ctx, "request finished", "duration", time.Since(start).Round(time.Millisecond)) - } - }() - - if err = h(w, r); err != nil && !clientDisconnected(ctx, err) { - writeErrorResponse(w, err) - } - } -} - -// clientDisconnected reports whether err is the cancellation that follows the -// client closing the connection: the request context is canceled and err -// carries that cancellation. A disconnect is routine, not a server failure, so -// callers log it at Debug rather than Error. A cancellation the action raised -// on its own while the request is still live does not match. -func clientDisconnected(ctx context.Context, err error) bool { - return errors.Is(err, context.Canceled) && errors.Is(ctx.Err(), context.Canceled) -} - -// clientError returns the message and status to send a client for err. Both -// the HTTP code (via [status.Name.HTTPCode]) and any wire status field must -// come from this one derivation so the two can never disagree. -// -// The status always comes from the error, so an error deliberately marked -// public reaches the client with its own code rather than falling through to -// 500. The message follows [wire.ClientMessage]. The full error is still -// logged server-side: by wrapHandler for request failures, and by the -// streaming runners for mid-stream flow failures. -func clientError(err error) (string, status.Name) { - code := status.Of(err) - // Only reached on a failure path, so an error that classifies as OK is - // itself the bug: the usual cause is a non-nil interface holding a nil - // *status.Error, which would otherwise report success on a request whose - // result was never written. - if code == status.OK { - code = status.Internal - } - msg, _ := wire.ClientMessage(err) - return msg, code -} - -// handler returns an HTTP handler function that serves the action with the provided options. -// Streaming responses are written in server-sent events (SSE) format. -func handler(a api.Action, opts *handlerOptions) func(http.ResponseWriter, *http.Request) error { - if a == nil { - return func(http.ResponseWriter, *http.Request) error { - return errors.New("action is nil; cannot serve") - } - } - key := a.Desc().Key - return func(w http.ResponseWriter, r *http.Request) error { - - var body wire.Request - if r.Body != nil && r.ContentLength > 0 { - defer r.Body.Close() - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - return status.PublicErrorf(status.ErrInvalidArgument, "%w", err) - } - } - - // Rejected before the streaming branch commits to SSE headers, so a - // non-bidi action receiving init fails with a proper HTTP 400 on - // every path rather than an in-band SSE error event on a 200. - if err := checkInitSupported(a, body.Init); err != nil { - return err - } - - run := func(ctx context.Context, input json.RawMessage, cb func(context.Context, json.RawMessage) error) (json.RawMessage, error) { - res, err := runActionWithOptionalInit(ctx, a, input, body.Init, cb) - if err != nil { - return nil, err - } - return res.Output, nil - } - - stream, err := parseBoolQueryParam(r, "stream") - if err != nil { - return err - } - stream = stream || r.Header.Get("Accept") == "text/event-stream" - - ctx, err := applyContextProviders(r.Context(), r, opts.ContextProviders, body.Data) - if err != nil { - return err - } - // Tell the action it is serving a client over the wire, so it can - // shape what it returns (an agent redacts internal error text). - ctx = wire.WithServedAction(ctx, key) - - if stream { - streamID := r.Header.Get("X-Genkit-Stream-Id") - - if streamID != "" && opts.StreamManager != nil { - return subscribeToStream(ctx, w, opts.StreamManager, streamID) - } - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Transfer-Encoding", "chunked") - - if opts.StreamManager != nil { - return runWithDurableStreaming(ctx, w, run, opts.StreamManager, body.Data) - } - - return runWithStreaming(ctx, w, run, body.Data) - } - - w.Header().Set("Content-Type", "application/json") - out, err := run(ctx, body.Data, nil) - if err != nil { - return err - } - return writeResultResponse(w, out) - } -} - -// applyContextProviders runs the configured context providers against the -// request and folds their results into ctx, so request-derived action -// context (e.g. auth from headers) is available to the action. input is -// handed to each provider as the request's decoded input -// ([core.RequestData.Input]). A nil or empty providers slice returns ctx -// unchanged. -func applyContextProviders(ctx context.Context, r *http.Request, providers []core.ContextProvider, input json.RawMessage) (context.Context, error) { - for _, ctxProvider := range providers { - headers := make(map[string]string, len(r.Header)) - for k, v := range r.Header { - headers[strings.ToLower(k)] = strings.Join(v, " ") - } - - actionCtx, err := ctxProvider(ctx, core.RequestData{ - Method: r.Method, - Headers: headers, - Input: input, - }) - if err != nil { - logger.Error(ctx, "context provider rejected the request", "error", err) - return ctx, err - } - - if existing := core.FromContext(ctx); existing != nil { - maps.Copy(existing, actionCtx) - actionCtx = existing - } - ctx = core.WithActionContext(ctx, actionCtx) - } - return ctx, nil -} - -// runJSONFunc abstracts over RunJSON and RunBidiJSON for the handler's -// execution paths. -type runJSONFunc = func(context.Context, json.RawMessage, func(context.Context, json.RawMessage) error) (json.RawMessage, error) - -// runWithStreaming executes the action with standard HTTP streaming (no durability). -func runWithStreaming(ctx context.Context, w http.ResponseWriter, run runJSONFunc, input json.RawMessage) error { - callback := func(ctx context.Context, msg json.RawMessage) error { - if err := writeSSEMessage(w, msg); err != nil { - return err - } - if f, ok := w.(http.Flusher); ok { - f.Flush() - } - return nil - } - - out, err := run(ctx, input, callback) - if clientDisconnected(ctx, err) { - // Nobody is left to read an error frame; wrapHandler logs the - // disconnect. - return err - } - if err != nil { - // The SSE frame carries only the redacted message and this function - // returns nil, so wrapHandler never sees the error: this log is the - // only server-side record of the real failure. - logger.Error(ctx, "streaming flow failed", "error", err) - if werr := writeSSEError(w, err); werr != nil { - return werr - } - return nil - } - return writeSSEResult(w, out) -} - -// runWithDurableStreaming executes the action with durable streaming support. -// Chunks are written to both the HTTP response and the stream manager for later replay. -// -// The flow execution is detached from the HTTP request context so that if the -// original client disconnects, the flow continues running and writing to durable -// storage. This allows other clients to subscribe to the stream and receive the -// remaining chunks and final result. -func runWithDurableStreaming(ctx context.Context, w http.ResponseWriter, run runJSONFunc, sm streaming.StreamManager, input json.RawMessage) error { - streamID := uuid.New().String() - - durableStream, err := sm.Open(ctx, streamID) - if err != nil { - return err - } - defer durableStream.Close() - - w.Header().Set("X-Genkit-Stream-Id", streamID) - - // Create a detached context for flow execution. This preserves context values - // (action context, tracing, logger) but won't be canceled when the HTTP client - // disconnects, allowing the flow to continue streaming to durable storage. - durableCtx := context.WithoutCancel(ctx) - - // Track whether the HTTP client is still connected. - clientGone := ctx.Done() - - callback := func(_ context.Context, msg json.RawMessage) error { - // Always write to durable storage regardless of client connection state. - durableStream.Write(durableCtx, msg) - - // Only attempt HTTP writes if the client is still connected. - select { - case <-clientGone: - return nil - default: - if err := writeSSEMessage(w, msg); err != nil { - return nil - } - if f, ok := w.(http.Flusher); ok { - f.Flush() - } - } - return nil - } - - out, err := run(durableCtx, input, callback) - if err != nil { - // As in runWithStreaming: the wire carries only the redacted message - // and wrapHandler never sees the error, so log the real failure here. - // The durable record is no substitute: it expires with the stream. - logger.Error(durableCtx, "streaming flow failed", "error", err) - durableStream.Error(durableCtx, err) - select { - case <-clientGone: - return nil - default: - writeSSEError(w, err) - } - return nil - } - - durableStream.Done(durableCtx, out) - select { - case <-clientGone: - return nil - default: - return writeSSEResult(w, out) - } -} - -// subscribeToStream subscribes to an existing durable stream and writes events to the HTTP response. -func subscribeToStream(ctx context.Context, w http.ResponseWriter, sm streaming.StreamManager, streamID string) error { - events, unsubscribe, err := sm.Subscribe(ctx, streamID) - if err != nil { - // Subscribe's contract is any NOT_FOUND error, not the in-tree - // streaming.ErrStreamNotFound sentinel specifically, so match on the - // status: a third-party StreamManager returning a plain NOT_FOUND - // gets the 204 that resuming clients key on, not a 404. - if status.Of(err) == status.NotFound { - w.WriteHeader(http.StatusNoContent) - return nil - } - return err - } - defer unsubscribe() - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Transfer-Encoding", "chunked") - - for event := range events { - switch event.Type { - case streaming.StreamEventChunk: - if err := writeSSEMessage(w, event.Chunk); err != nil { - return err - } - if f, ok := w.(http.Flusher); ok { - f.Flush() - } - case streaming.StreamEventDone: - if err := writeSSEResult(w, event.Output); err != nil { - return err - } - return nil - case streaming.StreamEventError: - streamErr := event.Err - if streamErr == nil { - streamErr = errors.New("unknown error") - } - if err := writeSSEError(w, streamErr); err != nil { - return err - } - return nil - } - } - - return nil -} - -// writeErrorResponse writes err as a non-streaming error response: a JSON -// [wire.Error] body under the HTTP status its status maps to, the same body JS -// servers send, so a client reads the status name rather than guessing it -// from an HTTP code that several statuses share. -func writeErrorResponse(w http.ResponseWriter, err error) { - msg, code := clientError(err) - w.Header().Set("Content-Type", "application/json") - w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(code.HTTPCode()) - json.NewEncoder(w).Encode(wire.Error{Status: code, Message: msg}) -} - -// writeResultResponse writes a JSON result response for non-streaming requests. -func writeResultResponse(w http.ResponseWriter, result json.RawMessage) error { - resp := wire.ResultResponse{Result: result} - data, err := json.Marshal(resp) - if err != nil { - return err - } - _, err = w.Write(data) - if err != nil { - return err - } - _, err = w.Write([]byte("\n")) - return err -} - -// writeSSEResult writes a JSON result as a server-sent event for streaming requests. -func writeSSEResult(w http.ResponseWriter, result json.RawMessage) error { - return writeSSEEvent(w, wire.ResultResponse{Result: result}) -} - -// writeSSEMessage writes a streaming chunk as a server-sent event. -func writeSSEMessage(w http.ResponseWriter, msg json.RawMessage) error { - return writeSSEEvent(w, wire.MessageResponse{Message: msg}) -} - -// writeSSEError writes an error as a server-sent event for streaming requests. -// Status and message come from the same clientError derivation, so the frame -// gets the identical redaction and OK-to-INTERNAL coercion as the HTTP path. -func writeSSEError(w http.ResponseWriter, flowErr error) error { - msg, code := clientError(flowErr) - return writeSSEEvent(w, wire.ErrorResponse{Error: &wire.Error{Status: code, Message: msg}}) -} - -// writeSSEEvent writes v as one server-sent event. -func writeSSEEvent(w http.ResponseWriter, v any) error { - data, err := json.Marshal(v) - if err != nil { - return err - } - _, err = fmt.Fprintf(w, "%s%s\n\n", wire.SSEDataPrefix, data) - return err -} - -func parseBoolQueryParam(r *http.Request, name string) (bool, error) { - b := false - if s := r.FormValue(name); s != "" { - var err error - b, err = strconv.ParseBool(s) - if err != nil { - return false, status.PublicErrorf(status.ErrInvalidArgument, "%w", err) - } - } - return b, nil -} diff --git a/go/server_test.go b/go/server_test.go deleted file mode 100644 index 032415d114..0000000000 --- a/go/server_test.go +++ /dev/null @@ -1,854 +0,0 @@ -// Copyright 2025 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package genkit - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "slices" - "strings" - "sync" - "testing" - - "github.com/genkit-ai/genkit-go/v2/core" - "github.com/genkit-ai/genkit-go/v2/core/api" - "github.com/genkit-ai/genkit-go/v2/core/status" - "github.com/genkit-ai/genkit-go/v2/core/x/streaming" - "github.com/genkit-ai/genkit-go/v2/internal/wire" -) - -func FakeContextProvider(ctx context.Context, req core.RequestData) (core.ActionContext, error) { - return core.ActionContext{ - "test": "action-context-value", - }, nil -} - -func TestHandler(t *testing.T) { - g := MustInit(context.Background()) - - successFlow := DefineFlow(g, "handlerSuccess", func(ctx context.Context, input string) (string, error) { - return "success", nil - }) - - genericErrorFlow := DefineFlow(g, "handlerGenericError", func(ctx context.Context, input string) (string, error) { - return "", errors.New("generic error message") - }) - - invalidArgFlow := DefineFlow(g, "handlerInvalidArg", func(ctx context.Context, input string) (string, error) { - return "", status.Errorf(status.ErrInvalidArgument, "field %q must be an RFC3339 timestamp", "startedAt") - }) - - notFoundFlow := DefineFlow(g, "handlerNotFound", func(ctx context.Context, input string) (string, error) { - return "", status.Errorf(status.ErrNotFound, "resource not found") - }) - - permissionDeniedFlow := DefineFlow(g, "handlerPermissionDenied", func(ctx context.Context, input string) (string, error) { - return "", status.Errorf(status.ErrPermissionDenied, "caller lacks roles/aiplatform.user on project acme-prod") - }) - - publicErrorFlow := DefineFlow(g, "handlerPublicError", func(ctx context.Context, input string) (string, error) { - return "", status.PublicErrorf(status.ErrInvalidArgument, "public error message") - }) - - t.Run("successful request returns 200 with response", func(t *testing.T) { - handler := Handler(successFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - t.Errorf("want status code %d, got %d", http.StatusOK, resp.StatusCode) - } - - if !strings.Contains(string(body), "success") { - t.Errorf("want response to contain 'success', got %q", string(body)) - } - }) - - t.Run("generic error returns 500 with error in response body", func(t *testing.T) { - handler := Handler(genericErrorFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusInternalServerError { - t.Errorf("want status code %d, got %d", http.StatusInternalServerError, resp.StatusCode) - } - - // The message is deliberately withheld: an unclassified error was never - // vetted as safe to return, so the client gets the status alone. - if strings.Contains(string(body), "generic error message") { - t.Errorf("internal message leaked to client: %q", string(body)) - } - }) - - t.Run("INVALID_ARGUMENT maps to 400", func(t *testing.T) { - handler := Handler(invalidArgFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusBadRequest { - t.Errorf("want status code %d for INVALID_ARGUMENT, got %d", http.StatusBadRequest, resp.StatusCode) - } - - // A JSON body naming the status, the format JS servers send and the - // remote agent client reads: an HTTP 400 alone does not say which - // status it was. The message is the generic label for the status, - // not the flow's own text. - if ct := resp.Header.Get("Content-Type"); ct != "application/json" { - t.Errorf("Content-Type = %q, want application/json", ct) - } - if got, want := decodeErrorBody(t, body), (wire.Error{Status: status.InvalidArgument, Message: "invalid argument"}); got != want { - t.Errorf("body = %+v, want %+v", got, want) - } - }) - - t.Run("NOT_FOUND maps to 404", func(t *testing.T) { - handler := Handler(notFoundFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusNotFound { - t.Errorf("want status code %d for NOT_FOUND, got %d", http.StatusNotFound, resp.StatusCode) - } - - if strings.Contains(string(body), "resource not found") { - t.Errorf("internal message leaked to client: %q", string(body)) - } - }) - - t.Run("PERMISSION_DENIED maps to 403", func(t *testing.T) { - handler := Handler(permissionDeniedFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusForbidden { - t.Errorf("want status code %d for PERMISSION_DENIED, got %d", http.StatusForbidden, resp.StatusCode) - } - - if got, want := decodeErrorBody(t, body).Message, "permission denied"; got != want { - t.Errorf("message = %q, want the generic %q", got, want) - } - if strings.Contains(string(body), "acme-prod") { - t.Errorf("internal detail leaked to client: %q", string(body)) - } - }) - - // A public error reaches the client with its own status and message. - t.Run("public error keeps its status and message", func(t *testing.T) { - handler := Handler(publicErrorFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusBadRequest { - t.Errorf("want status code %d, got %d", http.StatusBadRequest, resp.StatusCode) - } - - if !strings.Contains(string(body), "public error message") { - t.Errorf("want error message in response body, got %q", string(body)) - } - }) - - t.Run("error is written to response not returned", func(t *testing.T) { - handler := Handler(genericErrorFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - - // Verify error was written to response - if resp.StatusCode == http.StatusOK { - t.Error("want error status code, got 200") - } - }) -} - -func TestHandlerFunc(t *testing.T) { - g := MustInit(context.Background()) - - echoFlow := DefineFlow(g, "echo", func(ctx context.Context, input string) (string, error) { - return input, nil - }) - - errorFlow := DefineFlow(g, "error", func(ctx context.Context, input string) (string, error) { - return "", errors.New("flow error") - }) - - contextReaderFlow := DefineFlow(g, "contextReader", func(ctx context.Context, input []string) (string, error) { - actionCtx := core.FromContext(ctx) - if actionCtx == nil { - return "", errors.New("no action context") - } - - if len(input) == 0 { - return "", nil - } - - var values []string - for _, key := range input { - value, ok := actionCtx[key] - if !ok { - return "", fmt.Errorf("action context key %q not found", key) - } - - strValue, ok := value.(string) - if !ok { - return "", fmt.Errorf("action context value for key %q is not a string", key) - } - - values = append(values, strValue) - } - - return strings.Join(values, ","), nil - }) - - t.Run("basic handler", func(t *testing.T) { - handlerFunc := HandlerFunc(echoFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test-input"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if !strings.Contains(string(body), `"test-input"`) { - t.Errorf("want response to contain test-input, got %q", string(body)) - } - }) - - t.Run("action error", func(t *testing.T) { - handlerFunc := HandlerFunc(errorFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test-input"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err == nil { - t.Fatal("want error, got nil") - } - - if !strings.Contains(err.Error(), "flow error") { - t.Errorf("want error containing 'flow error', got %v", err) - } - }) - - t.Run("invalid JSON", func(t *testing.T) { - handlerFunc := HandlerFunc(echoFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":invalid-json}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err == nil { - t.Fatal("want error for invalid JSON, got nil") - } - - if !strings.Contains(err.Error(), "invalid character") { - t.Errorf("want error about invalid JSON, got %v", err) - } - }) - - t.Run("with context provider", func(t *testing.T) { - handlerFunc := HandlerFunc(contextReaderFlow, WithContextProviders(FakeContextProvider)) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":["test"]}`)) - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if !strings.Contains(string(body), "action-context-value") { - t.Errorf("want response to contain action-context-value, got %q", string(body)) - } - }) - - t.Run("multiple context providers", func(t *testing.T) { - handlerFunc := HandlerFunc(contextReaderFlow, WithContextProviders( - func(ctx context.Context, req core.RequestData) (core.ActionContext, error) { - return core.ActionContext{"provider1": "value1"}, nil - }, - func(ctx context.Context, req core.RequestData) (core.ActionContext, error) { - return core.ActionContext{"provider2": "value2"}, nil - }, - )) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":["provider1","provider2"]}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if !strings.Contains(string(body), "value1,value2") { - t.Errorf("want response to contain value1,value2, got %q", string(body)) - } - }) -} - -func TestStreamingHandlerFunc(t *testing.T) { - g := MustInit(context.Background()) - - streamingFlow := DefineStreamingFlow(g, "streaming", - func(ctx context.Context, input string, cb func(context.Context, string) error) (string, error) { - for _, c := range input { - if err := cb(ctx, string(c)); err != nil { - return "", err - } - } - return input + "-end", nil - }) - - errorStreamingFlow := DefineStreamingFlow(g, "errorStreaming", - func(ctx context.Context, input string, cb func(context.Context, string) error) (string, error) { - return "", errors.New("streaming error") - }) - - t.Run("streaming response", func(t *testing.T) { - handlerFunc := HandlerFunc(streamingFlow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"hello"}`)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - expected := `data: {"message":"h"} - -data: {"message":"e"} - -data: {"message":"l"} - -data: {"message":"l"} - -data: {"message":"o"} - -data: {"result":"hello-end"} - -` - if string(body) != expected { - t.Errorf("want streaming body:\n%q\n\nGot:\n%q", expected, string(body)) - } - }) - - t.Run("streaming error", func(t *testing.T) { - handlerFunc := HandlerFunc(errorStreamingFlow) - - req := httptest.NewRequest("POST", "/?stream=true", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - // For streaming, errors are sent as part of the SSE stream, not returned - if err != nil { - t.Errorf("want nil error (error should be in stream), got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - expected := `data: {"error":{"status":"INTERNAL","message":"internal"}} - -` - if string(body) != expected { - t.Errorf("want error body:\n%q\n\nGot:\n%q", expected, string(body)) - } - }) -} - -// recordingHandler is a slog.Handler that keeps every record it receives. -type recordingHandler struct { - mu sync.Mutex - records []slog.Record -} - -func (h *recordingHandler) Enabled(context.Context, slog.Level) bool { return true } - -func (h *recordingHandler) Handle(_ context.Context, r slog.Record) error { - h.mu.Lock() - defer h.mu.Unlock() - h.records = append(h.records, r.Clone()) - return nil -} - -func (h *recordingHandler) WithAttrs([]slog.Attr) slog.Handler { return h } -func (h *recordingHandler) WithGroup(string) slog.Handler { return h } - -// messages returns the messages of the records logged at level. -func (h *recordingHandler) messages(level slog.Level) []string { - h.mu.Lock() - defer h.mu.Unlock() - var msgs []string - for _, r := range h.records { - if r.Level == level { - msgs = append(msgs, r.Message) - } - } - return msgs -} - -func TestHandlerClientDisconnectLogging(t *testing.T) { - g := MustInit(context.Background()) - - // Each flow streams one chunk (when streaming), signals it is in flight, - // and then either waits for the request to end or fails on its own with - // context.Canceled while the request is still live. - defineFlow := func(name string, selfCancel bool, started chan<- struct{}) api.Action { - return DefineStreamingFlow(g, name, - func(ctx context.Context, _ string, cb func(context.Context, string) error) (string, error) { - if cb != nil { - if err := cb(ctx, "chunk"); err != nil { - return "", err - } - } - close(started) - if selfCancel { - return "", context.Canceled - } - <-ctx.Done() - return "", ctx.Err() - }) - } - - tests := []struct { - name string - stream bool - selfCancel bool - wantError bool - }{ - {name: "streaming client disconnects", stream: true}, - {name: "non-streaming client disconnects"}, - {name: "streaming flow cancels itself", stream: true, selfCancel: true, wantError: true}, - } - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - rec := &recordingHandler{} - prev := slog.Default() - slog.SetDefault(slog.New(rec)) - t.Cleanup(func() { slog.SetDefault(prev) }) - - started := make(chan struct{}) - h := Handler(defineFlow(fmt.Sprintf("disconnect%d", i), tt.selfCancel, started)) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - req := httptest.NewRequestWithContext(ctx, "POST", "/", strings.NewReader(`{"data":"x"}`)) - req.Header.Set("Content-Type", "application/json") - if tt.stream { - req.Header.Set("Accept", "text/event-stream") - } - - done := make(chan struct{}) - go func() { - defer close(done) - h(httptest.NewRecorder(), req) - }() - <-started - if !tt.selfCancel { - cancel() - } - <-done - - errs := rec.messages(slog.LevelError) - if tt.wantError { - if len(errs) == 0 { - t.Fatal("no ERROR record for a cancellation the flow raised itself") - } - return - } - if len(errs) > 0 { - t.Errorf("ERROR records for a client disconnect: %q", errs) - } - debug := rec.messages(slog.LevelDebug) - if n := len(slices.DeleteFunc(slices.Clone(debug), func(m string) bool { return m != "client disconnected" })); n != 1 { - t.Errorf("DEBUG records = %q, want exactly one %q", debug, "client disconnected") - } - if slices.Contains(debug, "request finished") { - t.Errorf("DEBUG records = %q, want no %q for a disconnect", debug, "request finished") - } - }) - } -} - -func TestDurableStreamingHandlerFunc(t *testing.T) { - g := MustInit(context.Background()) - - streamingFlow := DefineStreamingFlow(g, "durableStreaming", - func(ctx context.Context, input string, cb func(context.Context, string) error) (string, error) { - for _, c := range input { - if err := cb(ctx, string(c)); err != nil { - return "", err - } - } - return input + "-done", nil - }) - - t.Run("returns stream ID header", func(t *testing.T) { - sm := streaming.NewInMemoryStreamManager() - defer sm.Close() - handlerFunc := HandlerFunc(streamingFlow, WithStreamManager(sm)) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"hi"}`)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - streamID := resp.Header.Get("X-Genkit-Stream-Id") - if streamID == "" { - t.Error("want X-Genkit-Stream-Id header to be set") - } - - expected := `data: {"message":"h"} - -data: {"message":"i"} - -data: {"result":"hi-done"} - -` - if string(body) != expected { - t.Errorf("want streaming body:\n%q\n\nGot:\n%q", expected, string(body)) - } - }) - - t.Run("subscribe to completed stream", func(t *testing.T) { - sm := streaming.NewInMemoryStreamManager() - defer sm.Close() - handlerFunc := HandlerFunc(streamingFlow, WithStreamManager(sm)) - - // First request - run the stream to completion - req1 := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"ab"}`)) - req1.Header.Set("Content-Type", "application/json") - req1.Header.Set("Accept", "text/event-stream") - w1 := httptest.NewRecorder() - - err := handlerFunc(w1, req1) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp1 := w1.Result() - streamID := resp1.Header.Get("X-Genkit-Stream-Id") - if streamID == "" { - t.Fatal("want X-Genkit-Stream-Id header to be set") - } - - // Second request - subscribe to the completed stream - req2 := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"ignored"}`)) - req2.Header.Set("Content-Type", "application/json") - req2.Header.Set("Accept", "text/event-stream") - req2.Header.Set("X-Genkit-Stream-Id", streamID) - w2 := httptest.NewRecorder() - - err = handlerFunc(w2, req2) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp2 := w2.Result() - body2, _ := io.ReadAll(resp2.Body) - - // Should replay all chunks and the final result - expected := `data: {"message":"a"} - -data: {"message":"b"} - -data: {"result":"ab-done"} - -` - if string(body2) != expected { - t.Errorf("want replayed body:\n%q\n\nGot:\n%q", expected, string(body2)) - } - }) - - t.Run("subscribe to non-existent stream returns 204", func(t *testing.T) { - sm := streaming.NewInMemoryStreamManager() - defer sm.Close() - handlerFunc := HandlerFunc(streamingFlow, WithStreamManager(sm)) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"test"}`)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - req.Header.Set("X-Genkit-Stream-Id", "non-existent-stream-id") - w := httptest.NewRecorder() - - err := handlerFunc(w, req) - - if err != nil { - t.Errorf("want nil error, got %v", err) - } - - resp := w.Result() - - if resp.StatusCode != http.StatusNoContent { - t.Errorf("want status code %d, got %d", http.StatusNoContent, resp.StatusCode) - } - }) -} - -// TestHandlerBidiInitEnvelope verifies that an HTTP POST to a bidi action -// handler can supply Init via the request envelope's "init" field, alongside -// the existing "data" field. This is the production HTTP path for bidi -// actions invoked as one-shots. -func TestHandlerBidiInitEnvelope(t *testing.T) { - g := MustInit(context.Background()) - - type Config struct { - Prefix string `json:"prefix"` - } - - bidiAction := defineTestBidiAction(g.reg, api.ActionTypeCustom, "envelopeBidi", nil, - func(ctx context.Context, cfg Config, inCh <-chan string, outCh chan<- string) (string, error) { - for in := range inCh { - outCh <- cfg.Prefix + in - } - return "done", nil - }) - - t.Run("non-streaming envelope with init", func(t *testing.T) { - handler := Handler(bidiAction) - - body := `{"data":"hello","init":{"prefix":">> "}}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - respBody, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - t.Fatalf("status = %d, body = %s", resp.StatusCode, string(respBody)) - } - // Result should be "done"; the prefixed chunk goes to the streaming - // callback (nil here), so the final output is the function's return. - if !strings.Contains(string(respBody), `"done"`) { - t.Errorf("response body = %q, want it to contain \"done\"", string(respBody)) - } - }) - - t.Run("streaming envelope with init delivers prefixed chunk", func(t *testing.T) { - handler := HandlerFunc(bidiAction) - - // Use an HTML-safe prefix so json.Marshal doesn't escape it; that - // way the assertion can match the prefix literally in the SSE body. - body := `{"data":"hello","init":{"prefix":"PFX:"}}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - w := httptest.NewRecorder() - - if err := handler(w, req); err != nil { - t.Fatalf("handler: %v", err) - } - - respBody, _ := io.ReadAll(w.Result().Body) - if !strings.Contains(string(respBody), "PFX:hello") { - t.Errorf("response missing prefixed chunk; body = %q", string(respBody)) - } - if !strings.Contains(string(respBody), `"done"`) { - t.Errorf("response missing final result; body = %q", string(respBody)) - } - }) - - t.Run("envelope without init uses zero value", func(t *testing.T) { - handler := Handler(bidiAction) - - body := `{"data":"hello"}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - if resp.StatusCode != http.StatusOK { - respBody, _ := io.ReadAll(resp.Body) - t.Fatalf("status = %d, body = %s", resp.StatusCode, string(respBody)) - } - }) - - t.Run("envelope with malformed init returns 400", func(t *testing.T) { - handler := Handler(bidiAction) - - // Init is valid JSON but doesn't match the action's Config (prefix - // must be a string; here it's a number). - body := `{"data":"hello","init":{"prefix":42}}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - if resp.StatusCode != http.StatusBadRequest { - respBody, _ := io.ReadAll(resp.Body) - t.Errorf("status = %d, want %d; body = %s", resp.StatusCode, http.StatusBadRequest, string(respBody)) - } - }) - - t.Run("init on non-bidi flow returns 400", func(t *testing.T) { - plainFlow := DefineFlow(g, "envelopePlain", - func(ctx context.Context, in string) (string, error) { - return "out:" + in, nil - }) - handler := Handler(plainFlow) - - body := `{"data":"hello","init":{"prefix":">> "}}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - if resp.StatusCode != http.StatusBadRequest { - respBody, _ := io.ReadAll(resp.Body) - t.Errorf("status = %d, want %d; body = %s", resp.StatusCode, http.StatusBadRequest, string(respBody)) - } - }) - - t.Run("init on non-bidi flow returns 400 on streaming requests", func(t *testing.T) { - plainFlow := DefineFlow(g, "envelopePlainStream", - func(ctx context.Context, in string) (string, error) { - return "out:" + in, nil - }) - handler := Handler(plainFlow) - - // The rejection must happen before the handler commits to SSE: a - // streaming client should see an HTTP 400, not a 200 with an - // in-band error event. - body := `{"data":"hello","init":{"prefix":">> "}}` - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - w := httptest.NewRecorder() - - handler(w, req) - - resp := w.Result() - respBody, _ := io.ReadAll(resp.Body) - if resp.StatusCode != http.StatusBadRequest { - t.Errorf("status = %d, want %d; body = %s", resp.StatusCode, http.StatusBadRequest, string(respBody)) - } - if ct := resp.Header.Get("Content-Type"); strings.Contains(ct, "text/event-stream") { - t.Errorf("Content-Type = %q; response must not commit to SSE before rejecting init", ct) - } - }) -} - -// decodeErrorBody decodes a non-streaming error response body. -func decodeErrorBody(t *testing.T, body []byte) wire.Error { - t.Helper() - var e wire.Error - if err := json.Unmarshal(body, &e); err != nil { - t.Fatalf("error body %q is not a JSON wire error: %v", body, err) - } - return e -} diff --git a/go/servers_agent_test.go b/go/servers_agent_test.go deleted file mode 100644 index e43bdaedf6..0000000000 --- a/go/servers_agent_test.go +++ /dev/null @@ -1,547 +0,0 @@ -// Copyright 2026 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -// These tests exercise genkit.Handler serving experimental agents. Agents are -// defined via genkitx, which imports genkit, so the tests live in the -// external genkit_test package to avoid an import cycle. -package genkit_test - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" - "time" - - genkit "github.com/genkit-ai/genkit-go/v2" - "github.com/genkit-ai/genkit-go/v2/ai" - aix "github.com/genkit-ai/genkit-go/v2/ai/exp" - "github.com/genkit-ai/genkit-go/v2/ai/exp/localstore" - "github.com/genkit-ai/genkit-go/v2/core/api" - "github.com/genkit-ai/genkit-go/v2/core/status" - "github.com/genkit-ai/genkit-go/v2/exp" -) - -// agentHTTPResult mirrors the AgentOutput fields the agent handler tests -// assert on, decoded from the handler's {"result": ...} envelope. -type agentHTTPResult struct { - FinishReason string `json:"finishReason"` - SessionID string `json:"sessionId"` - SnapshotID string `json:"snapshotId"` - Message *ai.Message `json:"message"` - State json.RawMessage `json:"state"` - Error *struct { - Status string `json:"status"` - Message string `json:"message"` - Details map[string]any `json:"details"` - } `json:"error"` -} - -// TestHandlerAgent verifies that agents, being bidi actions, serve -// one-turn-at-a-time over the standard action handler: data carries -// the turn's AgentInput, init carries the session source (state for -// client-managed agents, sessionId/snapshotId for server-managed ones), and -// the conversation resumes across requests. It also pins the error contract: -// turn-tier failures resolve as a 200 with a failed AgentOutput (so the -// caller keeps the last-good state), while init-tier failures (a rejected -// session source) are hard HTTP errors. -func TestHandlerAgent(t *testing.T) { - g := genkit.MustInit(context.Background(), genkit.WithExperimental()) - var modelCalls atomic.Int64 - - // Replies "echo " where n is the number of messages the model saw, - // so resumed history is observable; fails when asked to. - genkit.DefineModel(g, "test/echo", &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true}}, - func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { - modelCalls.Add(1) - if len(req.Messages) == 0 { - return nil, status.Errorf(status.ErrInternal, "model saw empty messages") - } - last := req.Messages[len(req.Messages)-1] - if last.Role == ai.RoleUser && strings.Contains(last.Text(), "fail") { - return nil, status.Errorf(status.ErrResourceExhausted, "model on fire") - } - if cb != nil { - cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("chunk")}}) - } - return &ai.ModelResponse{ - Message: ai.NewModelTextMessage(fmt.Sprintf("echo %d", len(req.Messages))), - FinishReason: ai.FinishReasonStop, - }, nil - }) - - exp.DefineAgent[any](g, "agentClient", aix.InlinePrompt{ai.WithModelName("test/echo")}) - - store, err := localstore.NewFileSessionStore[any](t.TempDir()) - if err != nil { - t.Fatal(err) - } - exp.DefineAgent(g, "agentServer", aix.InlinePrompt{ai.WithModelName("test/echo")}, - aix.WithSessionStore(store), - ) - - // Agents register under their own action type, so they surface through - // ListAgents (and not ListFlows) and Handler serves them like any other - // action. - for _, a := range genkit.ListFlows(g) { - if a.Name() == "agentClient" || a.Name() == "agentServer" { - t.Fatalf("agent %q unexpectedly listed as a flow", a.Name()) - } - } - handlerFor := func(t *testing.T, name string) http.HandlerFunc { - t.Helper() - for _, a := range exp.ListAgents(g) { - if a.Name() == name { - return genkit.Handler(a) - } - } - t.Fatalf("agent %q not in ListAgents", name) - return nil - } - - post := func(t *testing.T, name, body string, stream bool) (int, string) { - t.Helper() - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - if stream { - req.Header.Set("Accept", "text/event-stream") - } - w := httptest.NewRecorder() - handlerFor(t, name)(w, req) - respBody, _ := io.ReadAll(w.Result().Body) - return w.Result().StatusCode, string(respBody) - } - - parseResult := func(t *testing.T, body string) agentHTTPResult { - t.Helper() - var envelope struct { - Result agentHTTPResult `json:"result"` - } - if err := json.Unmarshal([]byte(body), &envelope); err != nil { - t.Fatalf("unmarshal %q: %v", body, err) - } - return envelope.Result - } - - turn := func(text string) string { - return `{"data":{"message":{"role":"user","content":[{"text":"` + text + `"}]}}}` - } - turnWithInit := func(text, init string) string { - return `{"data":{"message":{"role":"user","content":[{"text":"` + text + `"}]}},"init":` + init + `}` - } - - t.Run("client-managed conversation across requests", func(t *testing.T) { - // Fresh turn: no init at all. - code, body := post(t, "agentClient", turn("hello"), false) - if code != http.StatusOK { - t.Fatalf("status = %d, body = %s", code, body) - } - res := parseResult(t, body) - if res.FinishReason != "stop" { - t.Errorf("finishReason = %q, want %q", res.FinishReason, "stop") - } - if res.SessionID == "" { - t.Error("missing sessionId") - } - if len(res.State) == 0 { - t.Fatal("client-managed output must carry state") - } - if got := res.Message.Text(); got != "echo 1" { - t.Errorf("message = %q, want %q", got, "echo 1") - } - - // Resume: round-trip the returned state through init. - code, body = post(t, "agentClient", turnWithInit("again", `{"state":`+string(res.State)+`}`), false) - if code != http.StatusOK { - t.Fatalf("resume status = %d, body = %s", code, body) - } - resumed := parseResult(t, body) - // The model saw the prior user/model exchange plus the new message. - if got := resumed.Message.Text(); got != "echo 3" { - t.Errorf("resumed message = %q, want %q", got, "echo 3") - } - if resumed.SessionID != res.SessionID { - t.Errorf("sessionId changed across resume: %q vs %q", resumed.SessionID, res.SessionID) - } - }) - - t.Run("server-managed conversation across requests", func(t *testing.T) { - code, body := post(t, "agentServer", turn("hello"), false) - if code != http.StatusOK { - t.Fatalf("status = %d, body = %s", code, body) - } - res := parseResult(t, body) - if len(res.State) != 0 { - t.Errorf("server-managed output must not inline state, got %s", res.State) - } - if res.SessionID == "" || res.SnapshotID == "" { - t.Fatalf("missing session/snapshot ID: %+v", res) - } - - code, body = post(t, "agentServer", turnWithInit("again", `{"sessionId":"`+res.SessionID+`"}`), false) - if code != http.StatusOK { - t.Fatalf("resume status = %d, body = %s", code, body) - } - resumed := parseResult(t, body) - if got := resumed.Message.Text(); got != "echo 3" { - t.Errorf("resumed message = %q, want %q", got, "echo 3") - } - }) - - t.Run("turn failure resolves as failed output with 200", func(t *testing.T) { - code, body := post(t, "agentClient", turn("fail"), false) - if code != http.StatusOK { - t.Fatalf("status = %d, want 200 (failure rides the output); body = %s", code, body) - } - res := parseResult(t, body) - if res.FinishReason != "failed" { - t.Errorf("finishReason = %q, want %q", res.FinishReason, "failed") - } - if res.Error == nil { - t.Fatalf("missing error in failed output: %s", body) - } - if res.Error.Status != "RESOURCE_EXHAUSTED" { - t.Errorf("error.status = %q, want RESOURCE_EXHAUSTED", res.Error.Status) - } - if res.Error.Message == "" { - t.Error("missing error.message") - } - if _, ok := res.Error.Details["stack"]; ok { - t.Error("error.details must not leak the in-process stack trace") - } - // The failed output still hands back the last-good state. - if len(res.State) == 0 { - t.Error("failed output must carry the last-good state") - } - }) - - t.Run("served failure hides internal error text", func(t *testing.T) { - // Dev keeps the full text for the Dev UI; this pins production. - t.Setenv("GENKIT_ENV", "prod") - code, body := post(t, "agentServer", turn("fail"), false) - if code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", code, body) - } - res := parseResult(t, body) - if res.Error == nil || res.Error.Status != "RESOURCE_EXHAUSTED" { - t.Fatalf("error = %+v, want RESOURCE_EXHAUSTED", res.Error) - } - if strings.Contains(res.Error.Message, "model on fire") { - t.Errorf("served output error = %q, leaks the internal text", res.Error.Message) - } - - // The failed turn's snapshot, read through the getSnapshot route. - snapAction := genkit.LookupAction(g, api.KeyFromName(api.ActionTypeAgentSnapshot, "agentServer")) - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":{"snapshotId":"`+res.SnapshotID+`"}}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - genkit.Handler(snapAction)(w, req) - snapBody, _ := io.ReadAll(w.Result().Body) - if strings.Contains(string(snapBody), "model on fire") || !strings.Contains(string(snapBody), "RESOURCE_EXHAUSTED") { - t.Errorf("served snapshot = %s, want the status without the internal text", snapBody) - } - - // The redaction belongs to the wire: a caller in this process keeps - // the full text. - out, err := exp.LookupAgent(g, "agentServer").RunText(context.Background(), "fail") - if err != nil { - t.Fatalf("RunText: %v", err) - } - if out.Error == nil || !strings.Contains(out.Error.Message, "model on fire") { - t.Errorf("in-process output error = %+v, want the full text", out.Error) - } - }) - - t.Run("missing turn message fails before model invocation", func(t *testing.T) { - before := modelCalls.Load() - code, body := post(t, "agentClient", `{"data":{}}`, false) - if code != http.StatusOK { - t.Fatalf("status = %d, want 200 (failure rides the output); body = %s", code, body) - } - res := parseResult(t, body) - if res.FinishReason != "failed" { - t.Errorf("finishReason = %q, want %q", res.FinishReason, "failed") - } - if res.Error == nil { - t.Fatalf("missing error in failed output: %s", body) - } - if res.Error.Status != "INVALID_ARGUMENT" { - t.Errorf("error.status = %q, want INVALID_ARGUMENT", res.Error.Status) - } - if !strings.Contains(res.Error.Message, "message") { - t.Errorf("error.message = %q, want substring %q", res.Error.Message, "message") - } - if got := modelCalls.Load(); got != before { - t.Fatalf("model calls = %d, want %d", got, before) - } - }) - - t.Run("init-tier failures are hard HTTP errors", func(t *testing.T) { - code, body := post(t, "agentServer", turnWithInit("hi", `{"snapshotId":"nope"}`), false) - if code != http.StatusNotFound { - t.Errorf("unknown snapshot: status = %d, want %d; body = %s", code, http.StatusNotFound, body) - } - - code, body = post(t, "agentServer", turnWithInit("hi", `{"state":{"messages":[]}}`), false) - if code != http.StatusBadRequest { - t.Errorf("state on server-managed: status = %d, want %d; body = %s", code, http.StatusBadRequest, body) - } - - code, body = post(t, "agentClient", turnWithInit("hi", `{"sessionId":"abc"}`), false) - if code != http.StatusBadRequest { - t.Errorf("sessionId on client-managed: status = %d, want %d; body = %s", code, http.StatusBadRequest, body) - } - - // data is required for one-shot runs: only a streaming session can - // start up and defer its first input. - code, body = post(t, "agentClient", `{"init": {}}`, false) - if code != http.StatusBadRequest { - t.Errorf("init without data: status = %d, want %d; body = %s", code, http.StatusBadRequest, body) - } - if !strings.Contains(body, "streaming session") { - t.Errorf("init without data: body should point the caller at streaming sessions; body = %s", body) - } - }) - - t.Run("served refusals name the caller's input, not the agent's setup", func(t *testing.T) { - t.Setenv("GENKIT_ENV", "prod") - _, body := post(t, "agentServer", turnWithInit("hi", `{"state":{"messages":[]}}`), false) - if !strings.Contains(body, "FAILED_PRECONDITION") || strings.Contains(body, "session store") { - t.Errorf("state on server-managed: body = %s, want the status without the store setup", body) - } - - snapAction := genkit.LookupAction(g, api.KeyFromName(api.ActionTypeAgentSnapshot, "agentServer")) - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":{}}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - genkit.Handler(snapAction)(w, req) - if b, _ := io.ReadAll(w.Result().Body); !strings.Contains(string(b), "snapshotId or sessionId is required") { - t.Errorf("getSnapshot without an ID: body = %s, want the missing field named", b) - } - }) - - t.Run("streaming turn delivers chunks then result", func(t *testing.T) { - code, body := post(t, "agentClient", turn("stream"), true) - if code != http.StatusOK { - t.Fatalf("status = %d, body = %s", code, body) - } - if !strings.Contains(body, "modelChunk") { - t.Errorf("missing modelChunk event; body = %s", body) - } - if !strings.Contains(body, "turnEnd") { - t.Errorf("missing turnEnd event; body = %s", body) - } - if !strings.Contains(body, `"result"`) { - t.Errorf("missing final result event; body = %s", body) - } - }) -} - -// TestHandlerAgentRef verifies that the typed agent ref is servable -// directly: the ref satisfies api.BidiAction, so Handler routes init -// through the bidi interface (session resume keeps working), and the -// companion actions plucked off the ref (GetSnapshotAction, -// AbortAction) serve the snapshot lifecycle on caller-chosen -// routes. Together they pin the detach → poll → abort story over plain -// HTTP. -func TestHandlerAgentRef(t *testing.T) { - g := genkit.MustInit(context.Background(), genkit.WithExperimental()) - - genkit.DefineModel(g, "test/echo", &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true}}, - func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { - return &ai.ModelResponse{ - Message: ai.NewModelTextMessage(fmt.Sprintf("echo %d", len(req.Messages))), - FinishReason: ai.FinishReasonStop, - }, nil - }) - - store, err := localstore.NewFileSessionStore[any](t.TempDir()) - if err != nil { - t.Fatal(err) - } - agent := exp.DefineAgent(g, "agentRef", aix.InlinePrompt{ai.WithModelName("test/echo")}, - aix.WithSessionStore(store), - ) - - // Handlers come straight off the ref; no registry iteration involved. - runHandler := genkit.Handler(agent) - getSnapshotHandler := genkit.Handler(agent.GetSnapshotAction()) - abortHandler := genkit.Handler(agent.AbortAction()) - - post := func(t *testing.T, h http.HandlerFunc, body string) (int, string) { - t.Helper() - req := httptest.NewRequest("POST", "/", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - h(w, req) - respBody, _ := io.ReadAll(w.Result().Body) - return w.Result().StatusCode, string(respBody) - } - - parseResult := func(t *testing.T, body string) agentHTTPResult { - t.Helper() - var envelope struct { - Result agentHTTPResult `json:"result"` - } - if err := json.Unmarshal([]byte(body), &envelope); err != nil { - t.Fatalf("unmarshal %q: %v", body, err) - } - return envelope.Result - } - - // snapshotHTTPResult covers both companion responses: getSnapshot - // returns the snapshot row, abort echoes {snapshotId, status}. - type snapshotHTTPResult struct { - SnapshotID string `json:"snapshotId"` - SessionID string `json:"sessionId"` - Status string `json:"status"` - State json.RawMessage `json:"state"` - } - parseSnapshot := func(t *testing.T, body string) snapshotHTTPResult { - t.Helper() - var envelope struct { - Result snapshotHTTPResult `json:"result"` - } - if err := json.Unmarshal([]byte(body), &envelope); err != nil { - t.Fatalf("unmarshal %q: %v", body, err) - } - return envelope.Result - } - - turn := func(text string) string { - return `{"data":{"message":{"role":"user","content":[{"text":"` + text + `"}]}}}` - } - - t.Run("turns resume through the ref's bidi interface", func(t *testing.T) { - code, body := post(t, runHandler, turn("hello")) - if code != http.StatusOK { - t.Fatalf("status = %d, body = %s", code, body) - } - res := parseResult(t, body) - if res.SessionID == "" || res.SnapshotID == "" { - t.Fatalf("missing session/snapshot ID: %+v", res) - } - - // Resume rides the init field, which the handler only accepts - // because the ref satisfies api.BidiAction. - code, body = post(t, runHandler, - `{"data":{"message":{"role":"user","content":[{"text":"again"}]}},"init":{"sessionId":"`+res.SessionID+`"}}`) - if code != http.StatusOK { - t.Fatalf("resume status = %d, body = %s", code, body) - } - if got := parseResult(t, body).Message.Text(); got != "echo 3" { - t.Errorf("resumed message = %q, want %q", got, "echo 3") - } - }) - - t.Run("getSnapshot serves the persisted snapshot", func(t *testing.T) { - code, body := post(t, runHandler, turn("snapshot me")) - if code != http.StatusOK { - t.Fatalf("turn status = %d, body = %s", code, body) - } - res := parseResult(t, body) - - code, body = post(t, getSnapshotHandler, `{"data":{"snapshotId":"`+res.SnapshotID+`"}}`) - if code != http.StatusOK { - t.Fatalf("getSnapshot status = %d, body = %s", code, body) - } - snap := parseSnapshot(t, body) - if snap.SnapshotID != res.SnapshotID || snap.SessionID != res.SessionID { - t.Errorf("snapshot identity = %q/%q, want %q/%q", snap.SnapshotID, snap.SessionID, res.SnapshotID, res.SessionID) - } - // The action normalizes the implicit empty status to "completed" - // so remote clients don't reimplement the default. - if snap.Status != "completed" { - t.Errorf("status = %q, want %q", snap.Status, "completed") - } - if len(snap.State) == 0 { - t.Error("snapshot must carry state") - } - }) - - t.Run("unknown snapshot IDs map to 404", func(t *testing.T) { - code, body := post(t, getSnapshotHandler, `{"data":{"snapshotId":"nope"}}`) - if code != http.StatusNotFound { - t.Errorf("getSnapshot: status = %d, want %d; body = %s", code, http.StatusNotFound, body) - } - code, body = post(t, abortHandler, `{"data":{"snapshotId":"nope"}}`) - if code != http.StatusNotFound { - t.Errorf("abort: status = %d, want %d; body = %s", code, http.StatusNotFound, body) - } - }) - - t.Run("abort on a terminal snapshot echoes its status", func(t *testing.T) { - code, body := post(t, runHandler, turn("terminal")) - if code != http.StatusOK { - t.Fatalf("turn status = %d, body = %s", code, body) - } - res := parseResult(t, body) - - code, body = post(t, abortHandler, `{"data":{"snapshotId":"`+res.SnapshotID+`"}}`) - if code != http.StatusOK { - t.Fatalf("abort status = %d, body = %s", code, body) - } - snap := parseSnapshot(t, body) - if snap.Status != "completed" { - t.Errorf("status = %q, want %q (abort of a terminal snapshot is a no-op)", snap.Status, "completed") - } - }) - - t.Run("detached turn finalizes in the background", func(t *testing.T) { - code, body := post(t, runHandler, - `{"data":{"detach":true,"message":{"role":"user","content":[{"text":"work in background"}]}}}`) - if code != http.StatusOK { - t.Fatalf("detach status = %d, body = %s", code, body) - } - res := parseResult(t, body) - if res.FinishReason != "detached" { - t.Fatalf("finishReason = %q, want %q; body = %s", res.FinishReason, "detached", body) - } - if res.SnapshotID == "" { - t.Fatal("detached output missing the pending snapshotId") - } - - // Poll the companion route until the background turn finalizes the - // pending row, the way a remote client would. - deadline := time.After(10 * time.Second) - for { - code, body := post(t, getSnapshotHandler, `{"data":{"snapshotId":"`+res.SnapshotID+`"}}`) - if code != http.StatusOK { - t.Fatalf("getSnapshot status = %d, body = %s", code, body) - } - snap := parseSnapshot(t, body) - if snap.Status != "pending" { - if snap.Status != "completed" { - t.Fatalf("final status = %q, want %q; body = %s", snap.Status, "completed", body) - } - if len(snap.State) == 0 { - t.Error("finalized snapshot must carry the cumulative state") - } - break - } - select { - case <-deadline: - t.Fatal("snapshot still pending after 10s") - case <-time.After(10 * time.Millisecond): - } - } - }) -} diff --git a/go/servers_leak_test.go b/go/servers_leak_test.go deleted file mode 100644 index 05755fac1f..0000000000 --- a/go/servers_leak_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2026 Google LLC -// -// 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. -// -// SPDX-License-Identifier: Apache-2.0 - -package genkit - -import ( - "context" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/genkit-ai/genkit-go/v2/core/api" - "github.com/genkit-ai/genkit-go/v2/core/status" -) - -// Each case below is a path that used to put internal failure detail on the -// wire. The flow HTTP boundary wrote err.Error() verbatim on every branch, so -// whatever an error happened to say reached the client. -func TestHandlerDoesNotLeakInternalDetail(t *testing.T) { - g := MustInit(context.Background()) - - // A provider error relayed verbatim. googlegenai wraps the raw SDK error, - // whose text can carry project and model resource paths, quota specifics, - // and permission detail. - providerFlow := DefineFlow(g, "leakProvider", func(ctx context.Context, in string) (string, error) { - return "", status.Errorf(status.Base(status.FromHTTPCode(429)), - "googleapi: Error 429: Quota exceeded for project 12345678, model projects/acme-prod/locations/us/models/x") - }) - - // An output schema violation. The message embeds the action key and a - // field-by-field dump of the shape the action failed to produce. - outputFlow := DefineFlow(g, "leakOutput", func(ctx context.Context, in string) (string, error) { - return "", status.Errorf(status.ErrInvalidOutput, - "invalid output from action %q: data did not match expected schema:\n- ssn: Invalid type. Expected: string", "/flow/leakOutput") - }) - - // An unclassified error from user code: the default path for anything not - // deliberately classified. - unclassifiedFlow := DefineFlow(g, "leakUnclassified", func(ctx context.Context, in string) (string, error) { - return "", errors.New("dial tcp 10.0.0.7:5432: connect: connection refused") - }) - - tests := []struct { - name string - flow api.Action - code int - secrets []string - }{ - {"provider error", providerFlow, http.StatusTooManyRequests, []string{"acme-prod", "12345678", "googleapi"}}, - {"output schema violation", outputFlow, http.StatusInternalServerError, []string{"ssn", "leakOutput", "expected schema"}}, - {"unclassified error", unclassifiedFlow, http.StatusInternalServerError, []string{"10.0.0.7", "connection refused"}}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - handler := Handler(tt.flow) - - req := httptest.NewRequest("POST", "/", strings.NewReader(`{"data":"x"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - handler(w, req) - - resp := w.Result() - body, _ := io.ReadAll(resp.Body) - - if resp.StatusCode != tt.code { - t.Errorf("status = %d, want %d", resp.StatusCode, tt.code) - } - for _, s := range tt.secrets { - if strings.Contains(string(body), s) { - t.Errorf("response leaked %q; body = %q", s, string(body)) - } - } - }) - } -} - -// The generic message must still name the status so a client can act on it, -// even though the specific message is withheld. -func TestGenericMessageStillCarriesStatus(t *testing.T) { - for _, tt := range []struct { - err error - want string - }{ - {status.Errorf(status.ErrNotFound, "model %q not found", "secret-internal-name"), "not found"}, - {status.Errorf(status.ErrPermissionDenied, "caller lacks roles/aiplatform.user"), "permission denied"}, - {errors.New("raw"), "internal"}, - } { - msg, public := status.PublicMessage(tt.err) - if public { - t.Errorf("PublicMessage(%v) reported public", tt.err) - } - if msg != tt.want { - t.Errorf("PublicMessage = %q, want %q", msg, tt.want) - } - } -} - -// GENKIT_ENV=dev keeps the full message, so local development is not blinded by -// the redaction that protects deployed servers. -func TestDevEnvironmentKeepsFullMessage(t *testing.T) { - t.Setenv("GENKIT_ENV", "dev") - - err := status.Errorf(status.ErrNotFound, "model %q not found", "googleai/nope") - msg, code := clientError(err) - if !strings.Contains(msg, "googleai/nope") { - t.Errorf("dev message = %q, want the full text", msg) - } - if code.HTTPCode() != http.StatusNotFound { - t.Errorf("code = %v, want %d", code, http.StatusNotFound) - } -} - -// A public error keeps its own status code. -func TestPublicErrorKeepsItsStatusCode(t *testing.T) { - for _, tt := range []struct { - err error - code int - }{ - {status.PublicErrorf(status.ErrUnauthenticated, "authorization header is required"), http.StatusUnauthorized}, - {status.PublicErrorf(status.ErrInvalidArgument, "field %q is required", "email"), http.StatusBadRequest}, - } { - msg, code := clientError(tt.err) - if code.HTTPCode() != tt.code { - t.Errorf("code = %v, want %d", code, tt.code) - } - if msg != tt.err.Error() { - t.Errorf("msg = %q, want the public message %q", msg, tt.err.Error()) - } - } -} - -// A non-nil error interface holding a nil *status.Error classifies as OK. The -// boundary is only reached on a failure path, so reporting 200 there would -// claim success for a request whose result was never written. -func TestTypedNilErrorDoesNotReportSuccess(t *testing.T) { - var typedNil *status.Error - msg, code := clientError(error(typedNil)) - if code != status.Internal { - t.Errorf("code = %v, want %v", code, status.Internal) - } - if msg != "" { - t.Errorf("msg = %q, want empty", msg) - } -} diff --git a/go/tests/test_app/main.go b/go/tests/test_app/main.go index d7d96b48a5..852502d0c2 100644 --- a/go/tests/test_app/main.go +++ b/go/tests/test_app/main.go @@ -27,6 +27,7 @@ import ( genkit "github.com/genkit-ai/genkit-go/v2" "github.com/genkit-ai/genkit-go/v2/ai" + "github.com/genkit-ai/genkit-go/v2/genkithttp" ) func main() { @@ -62,9 +63,9 @@ func main() { return fmt.Sprintf("done %d, streamed: %d times", count, i), nil }) - mux := http.NewServeMux() + mux := genkithttp.NewMux() for _, a := range genkit.ListFlows(g) { - mux.HandleFunc("POST /"+a.Name(), genkit.Handler(a)) + genkithttp.HandleAction(mux, a) } log.Fatal(http.ListenAndServe("127.0.0.1:3400", mux)) }