feat: track DingTalk delivery outcomes
This commit is contained in:
@@ -49,6 +49,10 @@ type QAAsker interface {
|
||||
Ask(ctx context.Context, req core.QARequest) (core.QAResult, error)
|
||||
}
|
||||
|
||||
type DeliveryRecorder interface {
|
||||
RecordDelivery(ctx context.Context, update core.DeliveryUpdate) error
|
||||
}
|
||||
|
||||
// StreamingQAAsker asks the QA backend with streaming observer support.
|
||||
type StreamingQAAsker interface {
|
||||
QAAsker
|
||||
@@ -257,6 +261,9 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
|
||||
if h.card != nil {
|
||||
cardReq := CardRequest{
|
||||
@@ -265,12 +272,18 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req
|
||||
ExternalChatID: req.ExternalChatID,
|
||||
Content: result.Answer,
|
||||
}
|
||||
if _, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil {
|
||||
if outTrackID, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil {
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodCard, outTrackID, "")
|
||||
return nil
|
||||
}
|
||||
log.Printf("DingTalk card delivery failed, falling back to markdown")
|
||||
}
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
if err := h.sendReply(ctx, webhookURL, result.Answer); err != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return err
|
||||
}
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, streamingQA StreamingQAAsker) error {
|
||||
@@ -291,7 +304,15 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return replyErr
|
||||
}
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Streaming observer with the configured update throttle (500ms by default).
|
||||
@@ -314,9 +335,9 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co
|
||||
|
||||
result, err := streamingQA.AskStream(ctx, req, observer)
|
||||
if err != nil || strings.TrimSpace(result.Answer) == "" {
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, qaErrorReply, true)
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true)
|
||||
}
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result.Answer, false)
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false)
|
||||
}
|
||||
|
||||
func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, eventQA EventQAAsker) error {
|
||||
@@ -333,7 +354,15 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r
|
||||
if askErr != nil {
|
||||
return h.sendReply(ctx, webhookURL, qaErrorReply)
|
||||
}
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
if result.Replayed && result.DeliveryStatus == core.DeliverySent {
|
||||
return nil
|
||||
}
|
||||
if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
return replyErr
|
||||
}
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
return nil
|
||||
}
|
||||
|
||||
pump := newCardUpdatePump(ctx, h.cardUpdateInterval, func(updateCtx context.Context, content string) error {
|
||||
@@ -358,12 +387,12 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r
|
||||
pump.Stop()
|
||||
|
||||
if err != nil || strings.TrimSpace(result.Answer) == "" {
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, qaErrorReply, true)
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true)
|
||||
}
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result.Answer, false)
|
||||
return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false)
|
||||
}
|
||||
|
||||
func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string, streamingCard StreamingCardSender, outTrackID, content string, isError bool) error {
|
||||
func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string, streamingCard StreamingCardSender, outTrackID string, result core.QAResult, content string, isError bool) error {
|
||||
timeout := h.finalDeliveryTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultHTTPTimeout
|
||||
@@ -375,6 +404,9 @@ func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string,
|
||||
updateErr := streamingCard.UpdateCard(finalCtx, outTrackID, content, true, isError)
|
||||
cancelFinal()
|
||||
if updateErr == nil {
|
||||
if !isError {
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodCard, outTrackID, "")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -382,7 +414,45 @@ func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string,
|
||||
// a fresh delivery window rather than reusing the expired finalCtx.
|
||||
fallbackCtx, cancelFallback := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
defer cancelFallback()
|
||||
return h.sendReply(fallbackCtx, webhookURL, content)
|
||||
if err := h.sendReply(fallbackCtx, webhookURL, content); err != nil {
|
||||
if !isError {
|
||||
h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if !isError {
|
||||
h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) recordDelivery(ctx context.Context, result core.QAResult, status, method, providerMessageID, failureCode string) {
|
||||
if strings.TrimSpace(result.TurnID) == "" || strings.TrimSpace(result.AnswerMessageID) == "" {
|
||||
return
|
||||
}
|
||||
recorder, ok := h.qa.(DeliveryRecorder)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
timeout := h.finalDeliveryTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultHTTPTimeout
|
||||
}
|
||||
auditCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
defer cancel()
|
||||
err := recorder.RecordDelivery(auditCtx, core.DeliveryUpdate{
|
||||
TenantKey: h.cfg.TenantKey,
|
||||
Channel: h.cfg.Channel,
|
||||
AnswerMessageID: result.AnswerMessageID,
|
||||
CorrelationID: result.TurnID,
|
||||
Status: status,
|
||||
DeliveryMethod: method,
|
||||
ProviderMessageID: providerMessageID,
|
||||
FailureCode: failureCode,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("DingTalk delivery audit update failed: status=%s method=%s", status, method)
|
||||
}
|
||||
}
|
||||
|
||||
func renderProgressEvent(event weknora.StreamEvent) string {
|
||||
|
||||
@@ -12,10 +12,12 @@ import (
|
||||
)
|
||||
|
||||
type fakeQA struct {
|
||||
called bool
|
||||
lastReq core.QARequest
|
||||
result core.QAResult
|
||||
err error
|
||||
called bool
|
||||
lastReq core.QARequest
|
||||
result core.QAResult
|
||||
err error
|
||||
deliveries []core.DeliveryUpdate
|
||||
deliveryErr error
|
||||
}
|
||||
|
||||
func (f *fakeQA) Ask(_ context.Context, req core.QARequest) (core.QAResult, error) {
|
||||
@@ -24,6 +26,11 @@ func (f *fakeQA) Ask(_ context.Context, req core.QARequest) (core.QAResult, erro
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
func (f *fakeQA) RecordDelivery(_ context.Context, update core.DeliveryUpdate) error {
|
||||
f.deliveries = append(f.deliveries, update)
|
||||
return f.deliveryErr
|
||||
}
|
||||
|
||||
type fakeReply struct {
|
||||
called bool
|
||||
lastURL string
|
||||
@@ -829,6 +836,8 @@ type fakeStreamingQA struct {
|
||||
streamCalled bool
|
||||
chunks []string // observer receives cumulated content after each chunk
|
||||
observerCaptured weknora.AnswerObserver
|
||||
deliveries []core.DeliveryUpdate
|
||||
deliveryErr error
|
||||
}
|
||||
|
||||
func (f *fakeStreamingQA) Ask(_ context.Context, req core.QARequest) (core.QAResult, error) {
|
||||
@@ -851,6 +860,11 @@ func (f *fakeStreamingQA) AskStream(_ context.Context, req core.QARequest, obser
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
func (f *fakeStreamingQA) RecordDelivery(_ context.Context, update core.DeliveryUpdate) error {
|
||||
f.deliveries = append(f.deliveries, update)
|
||||
return f.deliveryErr
|
||||
}
|
||||
|
||||
// fakeStreamingCard implements both FinalCardSender and StreamingCardSender.
|
||||
type fakeStreamingCard struct {
|
||||
// FinalCardSender
|
||||
@@ -1660,3 +1674,125 @@ func TestHandleEventStreamingFinalTimeoutUsesFreshMarkdownContext(t *testing.T)
|
||||
t.Fatalf("Markdown fallback received expired context: %v", reply.contextErr)
|
||||
}
|
||||
}
|
||||
|
||||
func deliveryQAResult() core.QAResult {
|
||||
return core.QAResult{
|
||||
TurnID: "turn-delivery-1", AnswerMessageID: "answer-delivery-1",
|
||||
DeliveryStatus: core.DeliveryGenerated, Answer: "delivery answer",
|
||||
}
|
||||
}
|
||||
|
||||
func requireDelivery(t *testing.T, deliveries []core.DeliveryUpdate, status, method, providerID, failureCode string) {
|
||||
t.Helper()
|
||||
if len(deliveries) != 1 {
|
||||
t.Fatalf("delivery updates=%d want=1: %+v", len(deliveries), deliveries)
|
||||
}
|
||||
got := deliveries[0]
|
||||
if got.TenantKey != "tenant-a" || got.Channel != "dingtalk" ||
|
||||
got.CorrelationID != "turn-delivery-1" || got.AnswerMessageID != "answer-delivery-1" ||
|
||||
got.Status != status || got.DeliveryMethod != method ||
|
||||
got.ProviderMessageID != providerID || got.FailureCode != failureCode {
|
||||
t.Fatalf("unexpected delivery update: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryAuditNonStreamingCardSuccess(t *testing.T) {
|
||||
qa := &fakeQA{result: deliveryQAResult()}
|
||||
h := newTestHandlerWithCard(t, qa, &fakeReply{}, &fakeCard{returnID: "track-delivery-1"})
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodCard, "track-delivery-1", "")
|
||||
}
|
||||
|
||||
func TestDeliveryAuditNonStreamingMarkdownFallbackAndFailure(t *testing.T) {
|
||||
t.Run("markdown succeeds", func(t *testing.T) {
|
||||
qa := &fakeQA{result: deliveryQAResult()}
|
||||
h := newTestHandlerWithCard(t, qa, &fakeReply{}, &fakeCard{err: errors.New("card failed")})
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
})
|
||||
t.Run("both fail", func(t *testing.T) {
|
||||
qa := &fakeQA{result: deliveryQAResult()}
|
||||
h := newTestHandlerWithCard(t, qa, &fakeReply{err: errors.New("markdown failed")}, &fakeCard{err: errors.New("card failed")})
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err == nil {
|
||||
t.Fatal("expected delivery error")
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeliveryAuditFailureAfterSuccessfulSendDoesNotTriggerRedelivery(t *testing.T) {
|
||||
qa := &fakeQA{result: deliveryQAResult(), deliveryErr: errors.New("database unavailable")}
|
||||
reply := &fakeReply{}
|
||||
card := &fakeCard{returnID: "track-delivery-1"}
|
||||
h := newTestHandlerWithCard(t, qa, reply, card)
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatalf("successful channel delivery must remain successful: %v", err)
|
||||
}
|
||||
if !card.called || reply.called || len(qa.deliveries) != 1 {
|
||||
t.Fatalf("delivery was duplicated: card=%v markdown=%v audits=%d", card.called, reply.called, len(qa.deliveries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryAuditSuppressesSentReplayBeforeNonStreamingDelivery(t *testing.T) {
|
||||
result := deliveryQAResult()
|
||||
result.Replayed = true
|
||||
result.DeliveryStatus = core.DeliverySent
|
||||
qa := &fakeQA{result: result}
|
||||
reply := &fakeReply{}
|
||||
card := &fakeCard{returnID: "must-not-send"}
|
||||
h := newTestHandlerWithCard(t, qa, reply, card)
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if card.called || reply.called || len(qa.deliveries) != 0 {
|
||||
t.Fatalf("sent replay must have zero delivery side effects: card=%v markdown=%v audits=%d", card.called, reply.called, len(qa.deliveries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryAuditStreamingCardAndMarkdown(t *testing.T) {
|
||||
t.Run("final card succeeds", func(t *testing.T) {
|
||||
qa := &fakeStreamingQA{result: deliveryQAResult(), chunks: []string{"delivery answer"}}
|
||||
card := &fakeStreamingCard{startID: "stream-track-1"}
|
||||
h := newTestHandlerWithStreaming(t, qa, &fakeReply{}, card)
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodCard, "stream-track-1", "")
|
||||
})
|
||||
t.Run("final card fails markdown succeeds", func(t *testing.T) {
|
||||
qa := &fakeStreamingQA{result: deliveryQAResult(), chunks: []string{"delivery answer"}}
|
||||
card := &fakeStreamingCard{startID: "stream-track-2", updateErr: errors.New("update failed")}
|
||||
h := newTestHandlerWithStreaming(t, qa, &fakeReply{}, card)
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodMarkdown, "", "")
|
||||
})
|
||||
t.Run("final card and markdown fail", func(t *testing.T) {
|
||||
qa := &fakeStreamingQA{result: deliveryQAResult(), chunks: []string{"delivery answer"}}
|
||||
card := &fakeStreamingCard{startID: "stream-track-3", updateErr: errors.New("update failed")}
|
||||
h := newTestHandlerWithStreaming(t, qa, &fakeReply{err: errors.New("markdown failed")}, card)
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err == nil {
|
||||
t.Fatal("expected delivery error")
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeliveryAuditEventStreamingProductionPath(t *testing.T) {
|
||||
qa := &fakeEventQA{
|
||||
fakeStreamingQA: fakeStreamingQA{result: deliveryQAResult()},
|
||||
events: []weknora.StreamEvent{{ResponseType: "answer", FullAnswer: "delivery answer", Done: true}},
|
||||
}
|
||||
card := &fakeStreamingCard{startID: "event-track-1"}
|
||||
h := newTestHandlerWithStreaming(t, qa, &fakeReply{}, card)
|
||||
h.cardUpdateInterval = time.Hour
|
||||
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodCard, "event-track-1", "")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user