From 16e636e3c55716131b5480a81296a61dfd63adcf Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Fri, 20 Nov 2026 01:57:31 +0000 Subject: [PATCH] Go SDK: failure hook The fourth of four PRs split from #190. WithFailureHook sets a hook that runs for each failure event the agent sends on DispatchEvents, and returns FailureActionDrop or FailureActionRetry, which is sent back as the answer. A panicking hook answers DROP and the stream continues. The SDK does not run the hook for its own failures. It classifies them into ReportInvocationRequest.failure: HANDLER_ERROR for an error or panic, TIMEOUT for a timeout, APPLICATION or RUNTIME by where it happened (a timeout during a Cortex API call, or one capped by the deadline, is RUNTIME). It does not start an invocation past its deadline. An agent without DispatchEvents answers Unimplemented; the SDK logs once and does not redial. Fixes found along the way: - invokeHandler let a timed-out handler write to the report while it was being sent. - Run(ctx) ignored cancellation: it opened its stream with context.Background(), and its exit flag was raced. The end-to-end test builds and runs the real agent; it is skipped with -short. Co-Authored-By: Claude Opus 5.5 --- sdks/go/README.md | 28 ++++ sdks/go/axon_agent.go | 170 +++++++++++++++----- sdks/go/axon_agent_test.go | 29 +++- sdks/go/e2e_failure_test.go | 260 ++++++++++++++++++++++++++++++ sdks/go/handler_context.go | 37 ++++- sdks/go/hooks.go | 173 ++++++++++++++++++++ sdks/go/hooks_test.go | 309 ++++++++++++++++++++++++++++++++++++ sdks/go/options.go | 1 + 8 files changed, 961 insertions(+), 46 deletions(-) create mode 100644 sdks/go/e2e_failure_test.go create mode 100644 sdks/go/hooks.go create mode 100644 sdks/go/hooks_test.go diff --git a/sdks/go/README.md b/sdks/go/README.md index 96caadd4..85ad3c9b 100644 --- a/sdks/go/README.md +++ b/sdks/go/README.md @@ -108,3 +108,31 @@ This will begin executing your handler every second. + +## Failure hooks + +`WithFailureHook` runs your own code for every failed invocation, including +ones only the agent sees (such as a webhook dropped because every handler was +busy). Use it to send failed messages somewhere you can replay them from. +Every failure goes through the agent: it sends each one to the hook and does +what the hook returns. This needs an agent that supports failure events. + +```go +agent := axon.NewAxonAgent( + axon.WithFailureHook(func(ctx context.Context, info axon.InvocationInfo, failure *axon.Failure) axon.FailureAction { + // info.Args holds the original webhook: "body", "content-type", "url" + deadLetters.Publish(info, failure) + if failure.Source == pb.FailureSource_RUNTIME && info.Attempt < 3 { + return axon.FailureActionRetry + } + return axon.FailureActionDrop + }), +) +``` + +`failure.Reason` is `HANDLER_ERROR`, `TIMEOUT` or `NO_RESOURCES`. +`failure.Source` says whether handler code (`APPLICATION`) or Axon +(`RUNTIME`) failed. A timeout during a Cortex API call counts as `RUNTIME`. +`CallerRejected` means the sender was told the message wasn't accepted (a +webhook got a 503). `FailureActionRetry` has the agent queue the invocation +again as its next attempt, up to 5 attempts; `FailureActionDrop` drops it. diff --git a/sdks/go/axon_agent.go b/sdks/go/axon_agent.go index 87e7d967..4af2279f 100644 --- a/sdks/go/axon_agent.go +++ b/sdks/go/axon_agent.go @@ -9,6 +9,7 @@ import ( "runtime" "strings" "sync" + "sync/atomic" "time" pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon" @@ -36,6 +37,8 @@ type Agent struct { logger *zap.Logger sleepOnError time.Duration done chan struct{} + + onFailure FailureHook } // NewAxonAgent creates a new AxonAgent with the specified options. You @@ -58,6 +61,7 @@ func NewAxonAgent(options ...Option) *Agent { logger: logger, sleepOnError: ao.sleepOnError, done: make(chan struct{}), + onFailure: ao.onFailure, } a.logger = logger @@ -231,12 +235,12 @@ const sleepErrorWait = 5 * time.Second // Run starts the agent and begins dispatching invocations to the registered handlers. func (a *Agent) Run(ctx context.Context) error { - exit := false + var exit atomic.Bool reregister := false sleepOnError := func(err error) { if a.sleepOnError == 0 { - exit = true + exit.Store(true) return } @@ -247,16 +251,33 @@ func (a *Agent) Run(ctx context.Context) error { runningHandlers := sync.WaitGroup{} + // Failure events stop after the last handler finishes, so a hook that + // retries from a handler still has a live agent connection. + eventsCtx, stopEvents := context.WithCancel(context.Background()) + eventsDone := make(chan struct{}) + if a.onFailure != nil { + go func() { + defer close(eventsDone) + a.runFailureEvents(eventsCtx) + }() + } else { + close(eventsDone) + } + defer func() { + stopEvents() + <-eventsDone + }() + go func() { select { case <-ctx.Done(): - exit = true + exit.Store(true) case <-a.done: - exit = true + exit.Store(true) } }() - for !exit { + for !exit.Load() { // aquire an agent and register handlers if needed // this allows agent crash/restart to recover @@ -277,7 +298,7 @@ func (a *Agent) Run(ctx context.Context) error { reregister = false - stream, err := stub.Dispatch(context.Background()) + stream, err := stub.Dispatch(ctx) if err != nil { sleepOnError(err) continue @@ -287,6 +308,7 @@ func (a *Agent) Run(ctx context.Context) error { err = stream.Send(&pb.DispatchRequest{ DispatchId: a.DispatchId, ClientVersion: version.Client, + FailureEvents: a.onFailure != nil, }) if err != nil { a.logger.Error("failed to send registration id", zap.Error(err)) @@ -350,7 +372,7 @@ func (a *Agent) processDispatchStream(ctx context.Context, stream grpc.BidiStrea req, err := stream.Recv() if err != nil { status, _ := status.FromError(err) - if err == io.EOF || status.Code() == codes.Unavailable { + if err == io.EOF || status.Code() == codes.Unavailable || ctx.Err() != nil { return nil } @@ -371,17 +393,27 @@ func (a *Agent) processDispatchStream(ctx context.Context, stream grpc.BidiStrea continue } + deadline, capped, expired := invokeDeadline(invoke, time.Now()) + if expired { + // The agent has already reported this one as failed; running + // it now would duplicate work a failure hook may be replaying. + a.logger.Warn("skipping invocation that expired before it could start", + zap.String("handler", invoke.HandlerName), + zap.String("invocation-id", invoke.InvocationId)) + continue + } + timeoutCtx := ctx cancel := func() {} - if invoke.TimeoutMs != 0 { - timeoutCtx, cancel = context.WithTimeout(context.Background(), time.Millisecond*time.Duration(invoke.TimeoutMs)) + if !deadline.IsZero() { + timeoutCtx, cancel = context.WithDeadline(context.Background(), deadline) } runningHandlers.Add(1) go func() { defer runningHandlers.Done() defer cancel() - a.invokeHandler(timeoutCtx, invoke) + a.invokeHandler(timeoutCtx, invoke, capped) }() case pb.DispatchMessageType_DISPATCH_MESSAGE_WORK_COMPLETED: a.logger.Info("work completed, shutting down") @@ -392,53 +424,112 @@ func (a *Agent) processDispatchStream(ctx context.Context, stream grpc.BidiStrea } } -func (a *Agent) invokeHandler(ctx context.Context, invoke *pb.DispatchHandlerInvoke) { +// deadlineMargin is how far ahead of the agent's deadline a handler must +// finish, so its report reaches the agent before the agent gives up on it. +const deadlineMargin = time.Second + +// invokeDeadline works out when a handler must finish: its own timeout, but no +// later than the agent's deadline. capped means the agent's deadline is the +// tighter one, i.e. the invocation waited before it got here. expired means +// it is already too late to start. +func invokeDeadline(invoke *pb.DispatchHandlerInvoke, now time.Time) (deadline time.Time, capped bool, expired bool) { + if invoke.TimeoutMs != 0 { + deadline = now.Add(time.Duration(invoke.TimeoutMs) * time.Millisecond) + } + if invoke.GetDeadline() == nil { + return deadline, false, false + } + agentDeadline := invoke.GetDeadline().AsTime().Add(-deadlineMargin) + if !now.Before(agentDeadline) { + return time.Time{}, false, true + } + if deadline.IsZero() || agentDeadline.Before(deadline) { + return agentDeadline, true, false + } + return deadline, false, false +} + +// invokeHandler runs one invocation. capped means its deadline came from the +// agent rather than its own timeout, so a timeout is time spent waiting, not +// the handler being slow. +func (a *Agent) invokeHandler(ctx context.Context, invoke *pb.DispatchHandlerInvoke, capped bool) { handlerInfo, ok := a.registeredHandlers[invoke.HandlerId] if !ok { a.logger.Error("handler not found", zap.String("handler", invoke.HandlerName)) return } - done := make(chan struct{}) - report := &pb.ReportInvocationRequest{ HandlerInvoke: invoke, StartClientTimestamp: timestamppb.Now(), } - - go func() { - apiStub := a.client.api() - - wrapped := zapcore.RegisterHooks(a.logger.Core(), func(entry zapcore.Entry) error { - report.Logs = append(report.Logs, &pb.Log{ - Level: entry.Level.CapitalString(), - Message: entry.Message, - Timestamp: timestamppb.New(entry.Time), - }) - return nil + start := time.Now() + + // The handler keeps running after a timeout, so it must not touch the + // report: logs go through a lock and the outcome over a channel. + var logsMu sync.Mutex + var logs []*pb.Log + wrapped := zapcore.RegisterHooks(a.logger.Core(), func(entry zapcore.Entry) error { + logsMu.Lock() + defer logsMu.Unlock() + logs = append(logs, &pb.Log{ + Level: entry.Level.CapitalString(), + Message: entry.Message, + Timestamp: timestamppb.New(entry.Time), }) + return nil + }) - loggerFromCore := zap.New(wrapped) - - handlerContext := NewHandlerContext(invoke, ctx, apiStub, loggerFromCore) - result, duration, err := a.executeHandlerWithRecover(handlerInfo, handlerContext) - report.DurationMs = int32(duration.Milliseconds()) - - if err != nil { - a.setReportError(report, "unexpected", err) - } else { - a.setReportResult(report, result) - } + loggerFromCore := zap.New(wrapped) + hctx := NewHandlerContext(invoke, ctx, a.client.api(), loggerFromCore) - close(done) + type handlerOutcome struct { + result any + duration time.Duration + err error + } + done := make(chan handlerOutcome, 1) + go func() { + result, duration, err := a.executeHandlerWithRecover(handlerInfo, hctx) + done <- handlerOutcome{result, duration, err} }() + var failure *Failure select { - case <-done: + case out := <-done: + report.DurationMs = int32(out.duration.Milliseconds()) + if out.err != nil { + a.setReportError(report, "unexpected", out.err) + failure = &Failure{ + Reason: pb.FailureReason_HANDLER_ERROR, + Source: pb.FailureSource_APPLICATION, + Message: out.err.Error(), + } + } else { + a.setReportResult(report, out.result) + } case <-ctx.Done(): + report.DurationMs = int32(time.Since(start).Milliseconds()) a.setReportError(report, "timeout", nil) + failure = &Failure{ + Reason: pb.FailureReason_TIMEOUT, + Source: pb.FailureSource_APPLICATION, + Message: fmt.Sprintf("handler did not finish within %dms", invoke.TimeoutMs), + } + if hc, ok := hctx.(*handlerContext); ok && hc.calls.blockedOnApi() { + failure.Source = pb.FailureSource_RUNTIME + failure.Message += " while waiting on a Cortex API call" + } else if capped { + failure.Source = pb.FailureSource_RUNTIME + failure.Message = "invocation waited for a free handler and ran out of time" + } } + logsMu.Lock() + report.Logs = logs + logs = nil + logsMu.Unlock() + if report.GetError() == nil { a.logger.Debug( "handler executed", @@ -453,6 +544,11 @@ func (a *Agent) invokeHandler(ctx context.Context, invoke *pb.DispatchHandlerInv zap.Any("error", report.GetError()), ) } + // The agent sends the failure back to the failure hook, so it is + // handled the same way as failures only the agent can see. + if failure != nil { + report.Failure = failure.toProto() + } _, err := a.client.agent().ReportInvocation(context.Background(), report) if err != nil { a.logger.Error("failed to report invocation", zap.Error(err)) diff --git a/sdks/go/axon_agent_test.go b/sdks/go/axon_agent_test.go index a6b965d6..adfe0638 100644 --- a/sdks/go/axon_agent_test.go +++ b/sdks/go/axon_agent_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "sync/atomic" "testing" "time" @@ -103,10 +104,11 @@ func TestInvokeHandlerWithTimeoutTriggered(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() - called := false + // The handler outlives the timeout, so it runs concurrently with the check. + var called atomic.Bool theHandler := func(ctx HandlerContext) error { - called = true + called.Store(true) time.Sleep(time.Millisecond * 10) return nil } @@ -117,7 +119,7 @@ func TestInvokeHandlerWithTimeoutTriggered(t *testing.T) { require.Equal(t, "timeout", reportedErr.Code) }) - require.True(t, called) + require.True(t, called.Load()) } @@ -237,6 +239,16 @@ func createAgent(controller *gomock.Controller) (*Agent, *mockGrpcClient) { type agentCallback func(*mockGrpcClient) func executeHandlerHelper(t *testing.T, controller *gomock.Controller, handler any, timeoutMs int, reportCallback func(*pb.ReportInvocationRequest), callback ...agentCallback) error { + return executeHandlerWithAgent(t, controller, handler, timeoutMs, reportCallback, func(_ *Agent, mock *mockGrpcClient) { + if len(callback) > 0 { + callback[0](mock) + } + }) +} + +// executeHandlerWithAgent runs one invocation of handler. configure can set +// up the agent and mocks before it runs. +func executeHandlerWithAgent(t *testing.T, controller *gomock.Controller, handler any, timeoutMs int, reportCallback func(*pb.ReportInvocationRequest), configure func(*Agent, *mockGrpcClient)) error { agent, mock := createAgent(controller) id := fmt.Sprintf("%d", time.Now().UnixNano()) @@ -257,6 +269,7 @@ func executeHandlerHelper(t *testing.T, controller *gomock.Controller, handler a }, ) + mock.lastStream = stream mock.agentStub.EXPECT().RegisterHandler(gomock.Any(), gomock.Any()).Return(&pb.RegisterHandlerResponse{Id: id}, nil) mock.agentStub.EXPECT().Dispatch(gomock.Any(), gomock.Any()).AnyTimes().Return(stream, nil) mock.agentStub.EXPECT().ReportInvocation(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( @@ -267,9 +280,7 @@ func executeHandlerHelper(t *testing.T, controller *gomock.Controller, handler a return &pb.ReportInvocationResponse{}, nil }) - if len(callback) > 0 { - callback[0](mock) - } + configure(agent, mock) options := []RegisterHandlerOption{ WithInvokeOption(pb.HandlerInvokeType_RUN_NOW, ""), @@ -302,6 +313,8 @@ func executeHandlerHelper(t *testing.T, controller *gomock.Controller, handler a type mockGrpcClient struct { apiStub *mock_axon.MockCortexApiClient agentStub *mock_axon.MockAxonAgentClient + + lastStream *mockBidiClient } func (m *mockGrpcClient) api() pb.CortexApiClient { @@ -318,6 +331,7 @@ type mockBidiClient struct { messages []*pb.DispatchMessage messageIndex int eofOnFinish bool + sent []*pb.DispatchRequest } func newBidiClient(messages ...*pb.DispatchMessage) *mockBidiClient { @@ -346,7 +360,8 @@ func (m *mockBidiClient) Recv() (*pb.DispatchMessage, error) { return msg, nil } -func (m *mockBidiClient) Send(*pb.DispatchRequest) error { +func (m *mockBidiClient) Send(req *pb.DispatchRequest) error { + m.sent = append(m.sent, req) if m.IsDone() && m.eofOnFinish { return io.EOF } diff --git a/sdks/go/e2e_failure_test.go b/sdks/go/e2e_failure_test.go new file mode 100644 index 00000000..6f0496a1 --- /dev/null +++ b/sdks/go/e2e_failure_test.go @@ -0,0 +1,260 @@ +package axon + +import ( + "context" + "fmt" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +// These tests run the SDK against a real agent built from ../../agent, and +// trigger invocations through its webhook endpoint. + +var ( + agentBinOnce sync.Once + agentBin string + agentBinErr error +) + +func buildAgent(t *testing.T) string { + agentBinOnce.Do(func() { + dir, err := os.MkdirTemp("", "axon-e2e") + if err != nil { + agentBinErr = err + return + } + agentBin = filepath.Join(dir, "axon-agent") + cmd := exec.Command("go", "build", "-o", agentBin, ".") + cmd.Dir = filepath.Join("..", "..", "agent") + out, err := cmd.CombinedOutput() + if err != nil { + agentBinErr = fmt.Errorf("building agent: %v\n%s", err, out) + } + }) + require.NoError(t, agentBinErr) + return agentBin +} + +// freePorts returns n distinct free ports. It holds each one open until all +// are picked, so the OS can't hand the same port out twice. +func freePorts(t *testing.T, n int) []int { + ports := make([]int, n) + for i := range ports { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + ports[i] = ln.Addr().(*net.TCPAddr).Port + } + return ports +} + +type realAgent struct { + grpcPort int + webhookPort int +} + +func startRealAgent(t *testing.T) *realAgent { + if testing.Short() { + t.Skip("starts a real agent") + } + bin := buildAgent(t) + ports := freePorts(t, 3) + a := &realAgent{grpcPort: ports[0], webhookPort: ports[1]} + + cmd := exec.Command(bin, "serve") + cmd.Env = append(os.Environ(), + "DRYRUN=true", + fmt.Sprintf("PORT=%d", a.grpcPort), + fmt.Sprintf("HTTP_PORT=%d", ports[2]), + fmt.Sprintf("WEBHOOK_PORT=%d", a.webhookPort), + "HANDLER_HISTORY_PATH="+t.TempDir(), + ) + logFile, err := os.Create(filepath.Join(t.TempDir(), "agent.log")) + require.NoError(t, err) + cmd.Stdout, cmd.Stderr = logFile, logFile + require.NoError(t, cmd.Start()) + t.Cleanup(func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + if t.Failed() { + logs, _ := os.ReadFile(logFile.Name()) + t.Logf("agent log:\n%s", logs) + } + }) + + require.Eventually(t, func() bool { + conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", a.grpcPort)) + if err == nil { + conn.Close() + } + return err == nil + }, 30*time.Second, 50*time.Millisecond, "agent never started listening") + return a +} + +// postWebhook sends body once the webhook is live, and returns the status the +// agent accepted it with. +func (a *realAgent) postWebhook(t *testing.T, id, body string) int { + url := fmt.Sprintf("http://127.0.0.1:%d/webhook/%s", a.webhookPort, id) + var status int + require.Eventually(t, func() bool { + resp, err := http.Post(url, "application/json", strings.NewReader(body)) + if err != nil { + return false + } + resp.Body.Close() + status = resp.StatusCode + // 404 until the SDK has registered and started dispatching. + return status != http.StatusNotFound + }, 10*time.Second, 50*time.Millisecond, "webhook never became available") + return status +} + +type e2eCall struct { + info InvocationInfo + failure *Failure +} + +// runAgainstRealAgent registers handler as webhook id on a fresh agent, with +// a failure hook that records each failure and asks for a retry. +func runAgainstRealAgent(t *testing.T, id string, handler Handler, opts ...RegisterHandlerOption) (*realAgent, chan e2eCall) { + a := startRealAgent(t) + failures := make(chan e2eCall, 10) + + logConfig := zap.NewDevelopmentConfig() + logConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel) + agent := NewAxonAgent( + WithHostport("127.0.0.1", a.grpcPort), + WithLoggerConfig(logConfig), + WithFailureHook(func(_ context.Context, info InvocationInfo, failure *Failure) FailureAction { + failures <- e2eCall{info, failure} + return FailureActionRetry + }), + ) + + opts = append(opts, WithInvokeOption(pb.HandlerInvokeType_WEBHOOK, id)) + _, err := agent.RegisterHandler(handler, opts...) + require.NoError(t, err) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _ = agent.Run(ctx) + }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(10 * time.Second): + } + }) + return a, failures +} + +type attempts struct { + mu sync.Mutex + bodies []string + ok chan string +} + +func newAttempts() *attempts { return &attempts{ok: make(chan string, 10)} } + +func (r *attempts) record(ctx HandlerContext) int { + r.mu.Lock() + defer r.mu.Unlock() + r.bodies = append(r.bodies, ctx.Args()["body"]) + return len(r.bodies) +} + +func requireFailure(t *testing.T, failures chan e2eCall) e2eCall { + select { + case call := <-failures: + return call + case <-time.After(15 * time.Second): + require.FailNow(t, "failure hook never ran") + return e2eCall{} + } +} + +func requireSucceeded(t *testing.T, r *attempts) string { + select { + case body := <-r.ok: + return body + case <-time.After(15 * time.Second): + require.FailNow(t, "retry never succeeded") + return "" + } +} + +func TestE2EHandlerErrorIsHookedAndRetried(t *testing.T) { + r := newAttempts() + a, failures := runAgainstRealAgent(t, "e2e-error", func(ctx HandlerContext) error { + if r.record(ctx) == 1 { + return fmt.Errorf("first attempt fails") + } + r.ok <- ctx.Args()["body"] + return nil + }) + + require.Equal(t, http.StatusOK, a.postWebhook(t, "e2e-error", `{"id": 42}`)) + + call := requireFailure(t, failures) + require.Equal(t, pb.FailureReason_HANDLER_ERROR, call.failure.Reason) + require.Equal(t, pb.FailureSource_APPLICATION, call.failure.Source) + require.Equal(t, "first attempt fails", call.failure.Message) + require.Equal(t, `{"id": 42}`, call.info.Args["body"]) + require.Equal(t, 1, call.info.Attempt) + + require.Equal(t, `{"id": 42}`, requireSucceeded(t, r), "the retry carries the original message") + + // It succeeded, so the hook does not run again. + select { + case extra := <-failures: + require.FailNow(t, "unexpected second failure", "%+v", extra.failure) + case <-time.After(time.Second): + } + r.mu.Lock() + require.Len(t, r.bodies, 2) + r.mu.Unlock() +} + +func TestE2ETimeoutIsHookedAndRetried(t *testing.T) { + r := newAttempts() + a, failures := runAgainstRealAgent(t, "e2e-timeout", func(ctx HandlerContext) error { + if r.record(ctx) == 1 { + <-ctx.Done() + return ctx.Err() + } + r.ok <- ctx.Args()["body"] + return nil + }, WithTimeout(500*time.Millisecond)) + + require.Equal(t, http.StatusOK, a.postWebhook(t, "e2e-timeout", `{"id": 7}`)) + + call := requireFailure(t, failures) + require.Equal(t, pb.FailureReason_TIMEOUT, call.failure.Reason) + require.Equal(t, pb.FailureSource_APPLICATION, call.failure.Source) + require.Equal(t, `{"id": 7}`, call.info.Args["body"]) + + require.Equal(t, `{"id": 7}`, requireSucceeded(t, r)) + + // The SDK reported the timeout itself, so the agent must not report it + // again once its grace period is over. + select { + case extra := <-failures: + require.FailNow(t, "timeout reported twice", "%+v", extra.failure) + case <-time.After(7 * time.Second): + } +} diff --git a/sdks/go/handler_context.go b/sdks/go/handler_context.go index 4e4fd632..cdbe9280 100644 --- a/sdks/go/handler_context.go +++ b/sdks/go/handler_context.go @@ -2,9 +2,11 @@ package axon import ( "context" + "sync/atomic" pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon" "go.uber.org/zap" + "google.golang.org/grpc" ) type handlerContextKey string @@ -22,7 +24,36 @@ type HandlerContext interface { type handlerContext struct { context.Context - args map[string]string + args map[string]string + calls *apiCallTracker +} + +// apiCallTracker records whether a Cortex API call was running when the +// handler's deadline hit, which makes the timeout Axon's fault, not the +// handler's. +type apiCallTracker struct { + inFlight atomic.Int32 + cutOff atomic.Bool +} + +func (t *apiCallTracker) blockedOnApi() bool { + return t.inFlight.Load() > 0 || t.cutOff.Load() +} + +type trackedApiClient struct { + pb.CortexApiClient + calls *apiCallTracker +} + +func (c trackedApiClient) Call(ctx context.Context, in *pb.CallRequest, opts ...grpc.CallOption) (*pb.CallResponse, error) { + c.calls.inFlight.Add(1) + defer c.calls.inFlight.Add(-1) + resp, err := c.CortexApiClient.Call(ctx, in, opts...) + if err != nil && ctx.Err() != nil { + // Set before inFlight drops, so a timeout check never sees neither. + c.calls.cutOff.Store(true) + } + return resp, err } func (h *handlerContext) Args() map[string]string { @@ -54,11 +85,13 @@ func NewHandlerContext(invoke *pb.DispatchHandlerInvoke, ctx context.Context, ap name := invoke.HandlerName logger = logger.With(zap.String("handler-name", name)) + calls := &apiCallTracker{} ctx = context.WithValue(ctx, logKey, logger) - ctx = context.WithValue(ctx, apiKey, api) + ctx = context.WithValue(ctx, apiKey, pb.CortexApiClient(trackedApiClient{CortexApiClient: api, calls: calls})) return &handlerContext{ Context: ctx, args: invoke.Args, + calls: calls, } } diff --git a/sdks/go/hooks.go b/sdks/go/hooks.go new file mode 100644 index 00000000..f2c7c90a --- /dev/null +++ b/sdks/go/hooks.go @@ -0,0 +1,173 @@ +package axon + +import ( + "context" + "errors" + "fmt" + "time" + + pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon" + "github.com/cortexapps/axon-go/version" + "go.uber.org/zap" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// InvocationInfo identifies one invocation for the failure hook. For a +// webhook, Args holds the inbound message: "body", "content-type" and "url". +type InvocationInfo struct { + InvocationID string + HandlerName string + InvokeType pb.HandlerInvokeType + Args map[string]string + // Attempt is 1 for the first delivery and counts up with each retry. + Attempt int + + invoke *pb.DispatchHandlerInvoke +} + +func newInvocationInfo(invoke *pb.DispatchHandlerInvoke) InvocationInfo { + return InvocationInfo{ + InvocationID: invoke.InvocationId, + HandlerName: invoke.HandlerName, + InvokeType: invoke.Reason, + Args: invoke.Args, + Attempt: max(int(invoke.Attempt), 1), + invoke: invoke, + } +} + +// Failure describes why an invocation failed. Source says whether handler +// code failed (APPLICATION) or Axon did (RUNTIME). +type Failure struct { + Reason pb.FailureReason + Source pb.FailureSource + Message string + // CallerRejected means whoever sent the invocation was told it was not + // accepted (a webhook sender got a 503), so it may arrive again. + CallerRejected bool +} + +func failureFromProto(f *pb.InvocationFailure) *Failure { + return &Failure{ + Reason: f.GetReason(), + Source: f.GetSource(), + Message: f.GetMessage(), + CallerRejected: f.GetCallerRejected(), + } +} + +func (f *Failure) toProto() *pb.InvocationFailure { + return &pb.InvocationFailure{ + Reason: f.Reason, + Source: f.Source, + Message: f.Message, + CallerRejected: f.CallerRejected, + } +} + +// FailureAction is what a FailureHook wants the agent to do with a failed +// invocation. +type FailureAction int + +const ( + // FailureActionDrop does nothing more with the invocation. + FailureActionDrop FailureAction = iota + // FailureActionRetry has the agent queue the invocation again as its + // next attempt. + FailureActionRetry +) + +func (a FailureAction) toProto() pb.FailureAction { + if a == FailureActionRetry { + return pb.FailureAction_FAILURE_ACTION_RETRY + } + return pb.FailureAction_FAILURE_ACTION_DROP +} + +// FailureHook runs for every failed invocation, wherever it failed: in this +// process, or in the agent, such as an invocation that never reached this +// process. The agent sends each failure here and applies the answer. +type FailureHook func(ctx context.Context, info InvocationInfo, failure *Failure) FailureAction + +// WithFailureHook sets a hook that runs for every failed invocation. +func WithFailureHook(hook FailureHook) Option { + return func(a *agentOptions) { + a.onFailure = hook + } +} + +func (a *Agent) runFailureHook(info InvocationInfo, failure *Failure) (action FailureAction) { + defer func() { + if r := recover(); r != nil { + a.logger.Error("panic in failure hook, dropping the invocation", + zap.String("invocation-id", info.InvocationID), zap.Any("panic", r)) + action = FailureActionDrop + } + }() + return a.onFailure(context.Background(), info, failure) +} + +var errEventsUnsupported = errors.New("agent does not support failure events") + +// runFailureEvents reads the agent's failure events until ctx is done. It has +// its own stream so it keeps reading while every handler is busy. +func (a *Agent) runFailureEvents(ctx context.Context) { + for ctx.Err() == nil { + err := a.readFailureEvents(ctx) + if errors.Is(err, errEventsUnsupported) { + a.logger.Warn("agent does not send failure events, upgrade the agent to use a failure hook") + return + } + if ctx.Err() != nil { + return + } + a.logger.Warn("failure event stream ended, reconnecting in "+sleepErrorWait.String(), zap.Error(err)) + select { + case <-ctx.Done(): + case <-time.After(sleepErrorWait): + } + } +} + +// readFailureEvents runs the hook for each failure the agent sends and +// answers with what it returned. +func (a *Agent) readFailureEvents(ctx context.Context) error { + stub := a.client.agent() + if stub == nil { + return fmt.Errorf("failed to create agent connection") + } + stream, err := stub.DispatchEvents(ctx) + if err != nil { + return err + } + err = stream.Send(&pb.DispatchEventsRequest{ + DispatchId: a.DispatchId, + ClientVersion: version.Client, + }) + if err != nil { + return err + } + for { + ev, err := stream.Recv() + if status.Code(err) == codes.Unimplemented { + return errEventsUnsupported + } + if err != nil { + return err + } + if ev.GetInvoke() == nil { + continue + } + action := a.runFailureHook(newInvocationInfo(ev.GetInvoke()), failureFromProto(ev.GetFailure())) + err = stream.Send(&pb.DispatchEventsRequest{ + Resolution: &pb.FailureResolution{ + InvocationId: ev.GetInvoke().GetInvocationId(), + Action: action.toProto(), + }, + }) + if err != nil { + return err + } + } +} diff --git a/sdks/go/hooks_test.go b/sdks/go/hooks_test.go new file mode 100644 index 00000000..02655e82 --- /dev/null +++ b/sdks/go/hooks_test.go @@ -0,0 +1,309 @@ +package axon + +import ( + "context" + "fmt" + "io" + "sync" + "testing" + "time" + + pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// reportedFailure runs handler once and returns the failure it reported to +// the agent, or nil. +func reportedFailure(t *testing.T, handler any, timeoutMs int, setup ...func(*mockGrpcClient)) *pb.InvocationFailure { + controller := gomock.NewController(t) + defer controller.Finish() + var reported *pb.ReportInvocationRequest + executeHandlerWithAgent(t, controller, handler, timeoutMs, + func(req *pb.ReportInvocationRequest) { reported = req }, + func(_ *Agent, mock *mockGrpcClient) { + for _, s := range setup { + s(mock) + } + }) + require.NotNil(t, reported) + return reported.GetFailure() +} + +func TestSuccessReportsNoFailure(t *testing.T) { + require.Nil(t, reportedFailure(t, func(ctx HandlerContext) error { return nil }, 0)) +} + +func TestHandlerErrorIsReportedAsApplicationFailure(t *testing.T) { + failure := reportedFailure(t, func(ctx HandlerContext) error { return fmt.Errorf("ohnoes") }, 0) + require.NotNil(t, failure) + require.Equal(t, pb.FailureReason_HANDLER_ERROR, failure.Reason) + require.Equal(t, pb.FailureSource_APPLICATION, failure.Source) + require.Equal(t, "ohnoes", failure.Message) +} + +func TestPanicIsReportedAsHandlerError(t *testing.T) { + failure := reportedFailure(t, func(ctx HandlerContext) error { panic("ohnoes") }, 0) + require.Equal(t, pb.FailureReason_HANDLER_ERROR, failure.Reason) + require.Equal(t, pb.FailureSource_APPLICATION, failure.Source) +} + +func TestSlowHandlerIsReportedAsApplicationTimeout(t *testing.T) { + failure := reportedFailure(t, func(ctx HandlerContext) error { + time.Sleep(50 * time.Millisecond) + return nil + }, 1) + require.Equal(t, pb.FailureReason_TIMEOUT, failure.Reason) + require.Equal(t, pb.FailureSource_APPLICATION, failure.Source) +} + +func TestTimeoutDuringApiCallIsReportedAsRuntime(t *testing.T) { + failure := reportedFailure(t, func(ctx HandlerContext) error { + _, err := ctx.CortexJsonApiCall("GET", "/api/v1/slow", "") + return err + }, 20, func(mock *mockGrpcClient) { + mock.apiStub.EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn( + func(ctx context.Context, req *pb.CallRequest, opts ...grpc.CallOption) (*pb.CallResponse, error) { + <-ctx.Done() + return nil, status.FromContextError(ctx.Err()).Err() + }) + }) + require.Equal(t, pb.FailureReason_TIMEOUT, failure.Reason) + require.Equal(t, pb.FailureSource_RUNTIME, failure.Source) +} + +func TestFailureHookNotRunLocally(t *testing.T) { + controller := gomock.NewController(t) + defer controller.Finish() + called := false + executeHandlerWithAgent(t, controller, func(ctx HandlerContext) error { return fmt.Errorf("ohnoes") }, 0, nil, + func(agent *Agent, mock *mockGrpcClient) { + // The agent sends the failure back as an event; it is not run here. + agent.onFailure = func(context.Context, InvocationInfo, *Failure) FailureAction { + called = true + return FailureActionDrop + } + expectEventStream(mock) + }) + require.False(t, called) +} + +// eventStream is a DispatchEvents stream: it delivers events, records the +// client's messages, and then blocks until the client stops reading. +type eventStream struct { + grpc.ClientStream + ctx context.Context + events chan *pb.DispatchEvent + err error + + mu sync.Mutex + sent []*pb.DispatchEventsRequest + // answered gets each resolution the client sends. + answered chan *pb.FailureResolution +} + +func (s *eventStream) Send(req *pb.DispatchEventsRequest) error { + s.mu.Lock() + s.sent = append(s.sent, req) + s.mu.Unlock() + if req.Resolution != nil { + s.answered <- req.Resolution + } + return nil +} + +func (s *eventStream) Recv() (*pb.DispatchEvent, error) { + if s.err != nil { + return nil, s.err + } + select { + case ev := <-s.events: + return ev, nil + case <-s.ctx.Done(): + return nil, io.EOF + } +} + +func (s *eventStream) CloseSend() error { return nil } + +// expectEventStream serves events on the first DispatchEvents stream the +// client opens, and returns the stream so the test can see its answers. +func expectEventStream(mock *mockGrpcClient, events ...*pb.DispatchEvent) *eventStream { + stream := &eventStream{ + ctx: context.Background(), + events: make(chan *pb.DispatchEvent, len(events)), + answered: make(chan *pb.FailureResolution, len(events)+1), + } + for _, ev := range events { + stream.events <- ev + } + mock.agentStub.EXPECT().DispatchEvents(gomock.Any(), gomock.Any()).AnyTimes().DoAndReturn( + func(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[pb.DispatchEventsRequest, pb.DispatchEvent], error) { + stream.ctx = ctx + return stream, nil + }) + return stream +} + +func failureEvent(id string, attempt int32) *pb.DispatchEvent { + return &pb.DispatchEvent{ + Invoke: &pb.DispatchHandlerInvoke{ + InvocationId: id, + HandlerName: "func1", + Reason: pb.HandlerInvokeType_WEBHOOK, + Args: map[string]string{"body": "payload-" + id}, + Attempt: attempt, + }, + Failure: &pb.InvocationFailure{ + Reason: pb.FailureReason_NO_RESOURCES, + Source: pb.FailureSource_RUNTIME, + Message: "dispatch queue is full", + CallerRejected: true, + }, + } +} + +// runWithEvents runs one handler invocation while the agent sends events. +// The handler holds the run open until every event has been answered. +func runWithEvents(t *testing.T, hook FailureHook, events ...*pb.DispatchEvent) *eventStream { + controller := gomock.NewController(t) + defer controller.Finish() + var stream *eventStream + answeredAll := make(chan struct{}) + executeHandlerWithAgent(t, controller, func(ctx HandlerContext) error { + select { + case <-answeredAll: + case <-time.After(5 * time.Second): + } + return nil + }, 0, nil, func(agent *Agent, mock *mockGrpcClient) { + agent.onFailure = hook + stream = expectEventStream(mock, events...) + go func() { + for { + stream.mu.Lock() + n := 0 + for _, req := range stream.sent { + if req.Resolution != nil { + n++ + } + } + stream.mu.Unlock() + if n >= len(events) { + close(answeredAll) + return + } + time.Sleep(5 * time.Millisecond) + } + }() + }) + return stream +} + +func TestFailureEventRunsHookAndAnswers(t *testing.T) { + var got InvocationInfo + var gotFailure *Failure + stream := runWithEvents(t, func(_ context.Context, info InvocationInfo, failure *Failure) FailureAction { + got, gotFailure = info, failure + return FailureActionRetry + }, failureEvent("lost-1", 2)) + + require.Equal(t, "lost-1", got.InvocationID) + require.Equal(t, "payload-lost-1", got.Args["body"]) + require.Equal(t, 2, got.Attempt) + require.Equal(t, pb.FailureReason_NO_RESOURCES, gotFailure.Reason) + require.True(t, gotFailure.CallerRejected) + + stream.mu.Lock() + defer stream.mu.Unlock() + require.Equal(t, "", stream.sent[0].GetResolution().GetInvocationId(), "the first message only identifies the client") + require.NotEmpty(t, stream.sent[0].DispatchId) + res := stream.sent[1].GetResolution() + require.Equal(t, "lost-1", res.InvocationId) + require.Equal(t, pb.FailureAction_FAILURE_ACTION_RETRY, res.Action) +} + +func TestFailureHookDropIsAnswered(t *testing.T) { + stream := runWithEvents(t, func(context.Context, InvocationInfo, *Failure) FailureAction { + return FailureActionDrop + }, failureEvent("lost-1", 1)) + require.Equal(t, pb.FailureAction_FAILURE_ACTION_DROP, (<-stream.answered).Action) +} + +func TestFailureHookPanicDrops(t *testing.T) { + stream := runWithEvents(t, func(context.Context, InvocationInfo, *Failure) FailureAction { + panic("hook bug") + }, failureEvent("lost-1", 1), failureEvent("lost-2", 1)) + // The panic is contained, and the stream keeps going. + require.Equal(t, "lost-1", (<-stream.answered).InvocationId) + second := <-stream.answered + require.Equal(t, "lost-2", second.InvocationId) + require.Equal(t, pb.FailureAction_FAILURE_ACTION_DROP, second.Action) +} + +func TestFailureEventsStopOnOlderAgent(t *testing.T) { + controller := gomock.NewController(t) + defer controller.Finish() + + executeHandlerWithAgent(t, controller, func(ctx HandlerContext) error { + time.Sleep(50 * time.Millisecond) + return nil + }, 0, nil, func(agent *Agent, mock *mockGrpcClient) { + agent.onFailure = func(context.Context, InvocationInfo, *Failure) FailureAction { return FailureActionDrop } + // Times(1): an agent without the RPC must not be redialed in a loop. + mock.agentStub.EXPECT().DispatchEvents(gomock.Any(), gomock.Any()).Times(1).Return( + &eventStream{err: status.Error(codes.Unimplemented, "unknown method DispatchEvents"), answered: make(chan *pb.FailureResolution, 1)}, nil) + }) +} + +func TestDispatchRequestAdvertisesFailureEvents(t *testing.T) { + for _, withHook := range []bool{false, true} { + t.Run(fmt.Sprint(withHook), func(t *testing.T) { + controller := gomock.NewController(t) + defer controller.Finish() + + var sent *mockBidiClient + executeHandlerWithAgent(t, controller, func(ctx HandlerContext) error { return nil }, 0, nil, + func(agent *Agent, mock *mockGrpcClient) { + if withHook { + agent.onFailure = func(context.Context, InvocationInfo, *Failure) FailureAction { return FailureActionDrop } + expectEventStream(mock) + } + sent = mock.lastStream + }) + require.Len(t, sent.sent, 1) + require.Equal(t, withHook, sent.sent[0].FailureEvents) + }) + } +} + +func TestInvokeDeadline(t *testing.T) { + now := time.Now() + agentDeadline := func(d time.Duration) *timestamppb.Timestamp { return timestamppb.New(now.Add(d)) } + + // Older agent: only the timeout counts. + d, capped, expired := invokeDeadline(&pb.DispatchHandlerInvoke{TimeoutMs: 1000}, now) + require.Equal(t, now.Add(time.Second), d) + require.False(t, capped) + require.False(t, expired) + + // Plenty of time left: the handler's own timeout is tighter. + d, capped, expired = invokeDeadline(&pb.DispatchHandlerInvoke{TimeoutMs: 1000, Deadline: agentDeadline(time.Minute)}, now) + require.Equal(t, now.Add(time.Second), d) + require.False(t, capped) + require.False(t, expired) + + // It waited before arriving: the agent's deadline, less the margin, wins. + d, capped, expired = invokeDeadline(&pb.DispatchHandlerInvoke{TimeoutMs: 10000, Deadline: agentDeadline(3 * time.Second)}, now) + require.WithinDuration(t, now.Add(2*time.Second), d, time.Millisecond) + require.True(t, capped) + require.False(t, expired) + + // Too late to start: the agent has reported it already. + _, _, expired = invokeDeadline(&pb.DispatchHandlerInvoke{TimeoutMs: 10000, Deadline: agentDeadline(500 * time.Millisecond)}, now) + require.True(t, expired) +} diff --git a/sdks/go/options.go b/sdks/go/options.go index bb862114..3f60e18b 100644 --- a/sdks/go/options.go +++ b/sdks/go/options.go @@ -28,6 +28,7 @@ type agentOptions struct { sleepOnError time.Duration version string maxReceiveMessageSize int + onFailure FailureHook } func resolveMaxReceiveMessageSize() int {