Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions sdks/go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
170 changes: 133 additions & 37 deletions sdks/go/axon_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"runtime"
"strings"
"sync"
"sync/atomic"
"time"

pb "github.com/cortexapps/axon-go/.generated/proto/github.com/cortexapps/axon"
Expand Down Expand Up @@ -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
Expand All @@ -58,6 +61,7 @@ func NewAxonAgent(options ...Option) *Agent {
logger: logger,
sleepOnError: ao.sleepOnError,
done: make(chan struct{}),
onFailure: ao.onFailure,
}

a.logger = logger
Expand Down Expand Up @@ -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
}

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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
}

Expand All @@ -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")
Expand All @@ -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",
Expand All @@ -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))
Expand Down
Loading
Loading