-
Notifications
You must be signed in to change notification settings - Fork 401
feat(controller): decouple A2A handler registration from controller reconcilation #1138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| package a2a | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "net" | ||
| "net/http" | ||
| "os" | ||
| "reflect" | ||
| "time" | ||
|
|
||
| "github.com/go-logr/logr" | ||
| "github.com/kagent-dev/kagent/go/api/v1alpha2" | ||
| agent_translator "github.com/kagent-dev/kagent/go/internal/controller/translator/agent" | ||
| authimpl "github.com/kagent-dev/kagent/go/internal/httpserver/auth" | ||
| common "github.com/kagent-dev/kagent/go/internal/utils" | ||
| "github.com/kagent-dev/kagent/go/pkg/auth" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| "k8s.io/client-go/tools/cache" | ||
| crcache "sigs.k8s.io/controller-runtime/pkg/cache" | ||
| ctrllog "sigs.k8s.io/controller-runtime/pkg/log" | ||
| "sigs.k8s.io/controller-runtime/pkg/manager" | ||
| a2aclient "trpc.group/trpc-go/trpc-a2a-go/client" | ||
| ) | ||
|
|
||
| type A2ARegistrar struct { | ||
| cache crcache.Cache | ||
| translator agent_translator.AdkApiTranslator | ||
| handlerMux A2AHandlerMux | ||
| a2aBaseUrl string | ||
| authenticator auth.AuthProvider | ||
| a2aBaseOptions []a2aclient.Option | ||
| } | ||
|
|
||
| var _ manager.Runnable = (*A2ARegistrar)(nil) | ||
|
|
||
| func NewA2ARegistrar( | ||
| cache crcache.Cache, | ||
| translator agent_translator.AdkApiTranslator, | ||
| mux A2AHandlerMux, | ||
| a2aBaseUrl string, | ||
| authenticator auth.AuthProvider, | ||
| streamingMaxBuf int, | ||
| streamingInitialBuf int, | ||
| streamingTimeout time.Duration, | ||
| ) *A2ARegistrar { | ||
| reg := &A2ARegistrar{ | ||
| cache: cache, | ||
| translator: translator, | ||
| handlerMux: mux, | ||
| a2aBaseUrl: a2aBaseUrl, | ||
| authenticator: authenticator, | ||
| a2aBaseOptions: []a2aclient.Option{ | ||
| a2aclient.WithTimeout(streamingTimeout), | ||
| a2aclient.WithBuffer(streamingInitialBuf, streamingMaxBuf), | ||
| debugOpt(), | ||
| }, | ||
| } | ||
|
|
||
| return reg | ||
| } | ||
|
|
||
| func (a *A2ARegistrar) NeedLeaderElection() bool { | ||
| return false | ||
| } | ||
|
|
||
| func (a *A2ARegistrar) Start(ctx context.Context) error { | ||
| log := ctrllog.FromContext(ctx).WithName("a2a-registrar") | ||
|
|
||
| informer, err := a.cache.GetInformer(ctx, &v1alpha2.Agent{}) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to get cache informer: %w", err) | ||
| } | ||
|
|
||
| if _, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ | ||
| AddFunc: func(obj interface{}) { | ||
| if agent, ok := obj.(*v1alpha2.Agent); ok { | ||
| if err := a.upsertAgentHandler(ctx, agent, log); err != nil { | ||
| log.Error(err, "failed to upsert A2A handler", "agent", common.GetObjectRef(agent)) | ||
| } | ||
| } | ||
| }, | ||
onematchfox marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| UpdateFunc: func(oldObj, newObj interface{}) { | ||
| oldAgent, ok1 := oldObj.(*v1alpha2.Agent) | ||
| newAgent, ok2 := newObj.(*v1alpha2.Agent) | ||
| if !ok1 || !ok2 { | ||
| return | ||
| } | ||
| if oldAgent.Generation != newAgent.Generation || !reflect.DeepEqual(oldAgent.Spec, newAgent.Spec) { | ||
| if err := a.upsertAgentHandler(ctx, newAgent, log); err != nil { | ||
| log.Error(err, "failed to upsert A2A handler", "agent", common.GetObjectRef(newAgent)) | ||
| } | ||
| } | ||
| }, | ||
| DeleteFunc: func(obj interface{}) { | ||
| agent, ok := obj.(*v1alpha2.Agent) | ||
| if !ok { | ||
| if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { | ||
| if a2, ok := tombstone.Obj.(*v1alpha2.Agent); ok { | ||
| agent = a2 | ||
| } | ||
| } | ||
| } | ||
| if agent == nil { | ||
| return | ||
| } | ||
| ref := common.GetObjectRef(agent) | ||
| a.handlerMux.RemoveAgentHandler(ref) | ||
| log.V(1).Info("removed A2A handler", "agent", ref) | ||
| }, | ||
| }); err != nil { | ||
| return fmt.Errorf("failed to add informer event handler: %w", err) | ||
| } | ||
|
|
||
| if ok := a.cache.WaitForCacheSync(ctx); !ok { | ||
| return fmt.Errorf("cache sync failed") | ||
| } | ||
|
|
||
| <-ctx.Done() | ||
| return nil | ||
| } | ||
|
|
||
| func (a *A2ARegistrar) upsertAgentHandler(ctx context.Context, agent *v1alpha2.Agent, log logr.Logger) error { | ||
| agentRef := types.NamespacedName{Namespace: agent.GetNamespace(), Name: agent.GetName()} | ||
| card := agent_translator.GetA2AAgentCard(agent) | ||
|
|
||
| client, err := a2aclient.NewA2AClient( | ||
| card.URL, | ||
| append( | ||
| a.a2aBaseOptions, | ||
| a2aclient.WithHTTPReqHandler( | ||
| authimpl.A2ARequestHandler( | ||
| a.authenticator, | ||
| agentRef, | ||
| ), | ||
| ), | ||
| )..., | ||
| ) | ||
| if err != nil { | ||
| return fmt.Errorf("create A2A client for %s: %w", agentRef, err) | ||
| } | ||
|
|
||
| cardCopy := *card | ||
| cardCopy.URL = fmt.Sprintf("%s/%s/", a.a2aBaseUrl, agentRef) | ||
|
|
||
onematchfox marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err := a.handlerMux.SetAgentHandler(agentRef.String(), client, cardCopy); err != nil { | ||
| return fmt.Errorf("set handler for %s: %w", agentRef, err) | ||
| } | ||
|
|
||
| log.V(1).Info("registered/updated A2A handler", "agent", agentRef) | ||
| return nil | ||
| } | ||
|
|
||
| func debugOpt() a2aclient.Option { | ||
| debugAddr := os.Getenv("KAGENT_A2A_DEBUG_ADDR") | ||
| if debugAddr != "" { | ||
| client := new(http.Client) | ||
| client.Transport = &http.Transport{ | ||
| DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { | ||
| var zeroDialer net.Dialer | ||
| return zeroDialer.DialContext(ctx, network, debugAddr) | ||
| }, | ||
| } | ||
| return a2aclient.WithHTTPClient(client) | ||
| } else { | ||
| return func(*a2aclient.A2AClient) {} | ||
| } | ||
| } | ||
onematchfox marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a reason you used the cache directly here instead of creating a
Controllerlike the rest of the k8s watchers? I usually prefer consistency across the various watchers so the codebase is easier to grok, but definitely open to this if there's a good reason.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I debated this a bit as well. I ended up just an informer implementation for a couple reasons.
Controllerscome with a bunch of overhead that I think is unnecessary for this implementation. We don't need the reconciliation semantics that controllers are designed for. The registrar doesn't need to loop and update to conmverge on desired state; it just needs to react to add/update/delete events to maintain an in-memory routing table. Additionally we don't need all the other overhead that comes with a controller including predicates, owning/watching relationships, woirk queues, rate limiting, retries, etc.A2ARegistrardeliberately, and explicilty, returnsfalsefromNeedLeaderElection()- rather than making this configurable when using aController.Finally, looking at it another way... if we were in future going to try and extract a
kagent-apicomponent, then it would feel very weird to me to be running a "Controller" within that component - but maybe that's just me 😆Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also.... having 2
AgentControllers in the same pod also feels really strange (and wrong).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think these are all very good reasons!