feat: add tenant-scoped audit query API

This commit is contained in:
姚章浩
2026-07-21 13:57:31 +08:00
parent 257a55a3f0
commit 56e3bf4686
12 changed files with 1205 additions and 13 deletions
+124
View File
@@ -0,0 +1,124 @@
package audit
import (
"context"
"errors"
"time"
)
var (
ErrNotFound = errors.New("turn not found")
ErrInvalidArgument = errors.New("invalid audit query")
)
// TurnStatus represents the status of a turn.
type TurnStatus string
const (
StatusProcessing TurnStatus = "processing"
StatusSucceeded TurnStatus = "succeeded"
StatusFailed TurnStatus = "failed"
StatusCancelled TurnStatus = "cancelled"
)
// TurnSummary is a lightweight representation of a turn for list views.
// It must never contain full question/answer text, error_message, WeKnora
// session/request IDs, or provider_message_id.
type TurnSummary struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Channel string `json:"channel"`
Status TurnStatus `json:"status"`
ConversationType string `json:"conversation_type"`
ConversationTitle string `json:"conversation_title,omitempty"`
ActorExternalID string `json:"actor_external_id,omitempty"`
ActorDisplayName string `json:"actor_display_name,omitempty"`
QuestionSummary string `json:"question_summary"`
AnswerSummary string `json:"answer_summary"`
ReferenceCount int `json:"reference_count"`
AnswerDeliveryStatus string `json:"answer_delivery_status,omitempty"`
AnswerDeliveryMethod string `json:"answer_delivery_method,omitempty"`
}
// SafeReference is a reference with only safe fields exposed.
// Content and Raw are never included.
type SafeReference struct {
ID string `json:"id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeTitle string `json:"knowledge_title"`
Score float64 `json:"score"`
}
// SafeMedia is a media audit entry with only safe metadata.
type SafeMedia struct {
Type string `json:"type"`
MIMEType string `json:"mime_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
}
// MessageMeta provides request/answer message metadata.
type MessageMeta struct {
ID string `json:"id"`
Direction string `json:"direction"`
Role string `json:"role"`
MessageType string `json:"message_type"`
Status string `json:"status"`
ActorName string `json:"actor_name,omitempty"`
CreatedAt time.Time `json:"created_at"`
DeliveredAt *time.Time `json:"delivered_at,omitempty"`
DeliveryMethod string `json:"delivery_method,omitempty"`
FailureCode string `json:"failure_code,omitempty"`
}
// TurnDetail is the full detail view of a turn. It must never include
// error_message, WeKnora session/request ID, provider_message_id,
// sessionWebhook, tokens, raw API/error, or Reference.Content/Raw.
type TurnDetail struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Channel string `json:"channel"`
Status TurnStatus `json:"status"`
ConversationType string `json:"conversation_type"`
ConversationTitle string `json:"conversation_title,omitempty"`
ActorExternalID string `json:"actor_external_id,omitempty"`
ActorDisplayName string `json:"actor_display_name,omitempty"`
Question string `json:"question"`
Answer string `json:"answer"`
References []SafeReference `json:"references,omitempty"`
Media []SafeMedia `json:"media,omitempty"`
RequestMessage *MessageMeta `json:"request_message,omitempty"`
AnswerMessage *MessageMeta `json:"answer_message,omitempty"`
ReferenceCount int `json:"reference_count"`
AnswerDeliveryStatus string `json:"answer_delivery_status,omitempty"`
AnswerDeliveryMethod string `json:"answer_delivery_method,omitempty"`
}
// ListTurnsRequest is the input for listing turns.
type ListTurnsRequest struct {
Limit int
Cursor string
Channel string
Status TurnStatus
}
// ListTurnsResult is the output of a list turns query.
type ListTurnsResult struct {
Items []TurnSummary `json:"items"`
NextCursor string `json:"next_cursor,omitempty"`
}
type ListQuery struct {
Limit int
Channel string
Status TurnStatus
BeforeCreatedAt *time.Time
BeforeID string
}
// TurnRepository is the data access interface for audit queries.
type TurnRepository interface {
ListTurns(ctx context.Context, tenantKey string, query ListQuery) ([]TurnSummary, error)
GetTurn(ctx context.Context, tenantKey, turnID string) (TurnDetail, error)
}
+54
View File
@@ -0,0 +1,54 @@
package audit
import (
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
)
const maxCursorLength = 512
type cursorData struct {
CreatedAt time.Time `json:"t"`
ID string `json:"id"`
}
func encodeCursor(createdAt time.Time, id string) string {
data := cursorData{
CreatedAt: createdAt,
ID: id,
}
payload, err := json.Marshal(data)
if err != nil {
// This should never happen for a simple struct.
panic("encodeCursor marshal: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(payload)
}
func encodeCursorString(payload string) string {
return base64.RawURLEncoding.EncodeToString([]byte(payload))
}
func decodeCursor(cursor string) (cursorData, error) {
if strings.TrimSpace(cursor) == "" {
return cursorData{}, errors.New("empty cursor")
}
if len(cursor) > maxCursorLength {
return cursorData{}, errors.New("cursor too long")
}
payload, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return cursorData{}, errors.New("invalid cursor encoding")
}
var data cursorData
if err := json.Unmarshal(payload, &data); err != nil {
return cursorData{}, errors.New("invalid cursor payload")
}
if data.CreatedAt.IsZero() || data.ID == "" {
return cursorData{}, errors.New("incomplete cursor data")
}
return data, nil
}
+63
View File
@@ -0,0 +1,63 @@
package audit
import (
"strings"
"testing"
"time"
)
func TestCursorRoundTrip(t *testing.T) {
now := time.Date(2026, 7, 21, 12, 0, 0, 0, time.UTC)
cursor := encodeCursor(now, "turn-abc-123")
decoded, err := decodeCursor(cursor)
if err != nil {
t.Fatalf("decodeCursor: %v", err)
}
if !decoded.CreatedAt.Equal(now) {
t.Fatalf("CreatedAt=%v, want %v", decoded.CreatedAt, now)
}
if decoded.ID != "turn-abc-123" {
t.Fatalf("ID=%q, want %q", decoded.ID, "turn-abc-123")
}
}
func TestDecodeCursorRejectsEmpty(t *testing.T) {
_, err := decodeCursor("")
if err == nil {
t.Fatal("expected error for empty cursor")
}
}
func TestDecodeCursorRejectsInvalidBase64(t *testing.T) {
_, err := decodeCursor("!!!not-valid-base64!!!")
if err == nil {
t.Fatal("expected error for invalid base64")
}
}
func TestDecodeCursorRejectsTruncated(t *testing.T) {
// Create a valid cursor then truncate it
cursor := encodeCursor(time.Now().UTC(), "id")
truncated := cursor[:len(cursor)-3]
_, err := decodeCursor(truncated)
if err == nil {
t.Fatal("expected error for truncated cursor")
}
}
func TestDecodeCursorRejectsTooLong(t *testing.T) {
// 1024 bytes should exceed max cursor length
_, err := decodeCursor(strings.Repeat("A", 1024))
if err == nil {
t.Fatal("expected error for too-long cursor")
}
}
func TestDecodeCursorRejectsMissingFields(t *testing.T) {
// Invalid JSON payload (not a valid cursor struct)
// We create a cursor-like string that decodes but has missing fields
_, err := decodeCursor(encodeCursorString("{}"))
if err == nil {
t.Fatal("expected error for missing fields in cursor")
}
}
+97
View File
@@ -0,0 +1,97 @@
package audit
import (
"context"
"fmt"
"strings"
)
const (
defaultLimit = 20
maxLimit = 100
maxChannelLen = 128
maxTurnIDLen = 128
maxSummaryLen = 200
)
type Service struct {
tenantKey string
repo TurnRepository
}
func NewService(tenantKey string, repo TurnRepository) (*Service, error) {
tenantKey = strings.TrimSpace(tenantKey)
if tenantKey == "" || repo == nil {
return nil, fmt.Errorf("%w: tenant and repository are required", ErrInvalidArgument)
}
return &Service{tenantKey: tenantKey, repo: repo}, nil
}
func (s *Service) ListTurns(ctx context.Context, req ListTurnsRequest) (ListTurnsResult, error) {
if req.Limit == 0 {
req.Limit = defaultLimit
}
if req.Limit < 1 || req.Limit > maxLimit {
return ListTurnsResult{}, fmt.Errorf("%w: limit must be between 1 and %d", ErrInvalidArgument, maxLimit)
}
req.Channel = strings.TrimSpace(req.Channel)
if len(req.Channel) > maxChannelLen {
return ListTurnsResult{}, fmt.Errorf("%w: channel too long", ErrInvalidArgument)
}
if !validStatus(req.Status) {
return ListTurnsResult{}, fmt.Errorf("%w: invalid status", ErrInvalidArgument)
}
query := ListQuery{Limit: req.Limit + 1, Channel: req.Channel, Status: req.Status}
if req.Cursor != "" {
cursor, err := decodeCursor(req.Cursor)
if err != nil {
return ListTurnsResult{}, fmt.Errorf("%w: invalid cursor", ErrInvalidArgument)
}
query.BeforeCreatedAt = &cursor.CreatedAt
query.BeforeID = cursor.ID
}
items, err := s.repo.ListTurns(ctx, s.tenantKey, query)
if err != nil {
return ListTurnsResult{}, err
}
for i := range items {
items[i].QuestionSummary = truncateRunes(items[i].QuestionSummary, maxSummaryLen)
items[i].AnswerSummary = truncateRunes(items[i].AnswerSummary, maxSummaryLen)
}
result := ListTurnsResult{Items: items}
if result.Items == nil {
result.Items = []TurnSummary{}
}
if len(result.Items) > req.Limit {
result.Items = result.Items[:req.Limit]
last := result.Items[len(result.Items)-1]
result.NextCursor = encodeCursor(last.CreatedAt, last.ID)
}
return result, nil
}
func (s *Service) GetTurn(ctx context.Context, turnID string) (TurnDetail, error) {
turnID = strings.TrimSpace(turnID)
if turnID == "" || len(turnID) > maxTurnIDLen {
return TurnDetail{}, fmt.Errorf("%w: invalid turn id", ErrInvalidArgument)
}
return s.repo.GetTurn(ctx, s.tenantKey, turnID)
}
func validStatus(status TurnStatus) bool {
switch status {
case "", StatusProcessing, StatusSucceeded, StatusFailed, StatusCancelled:
return true
default:
return false
}
}
func truncateRunes(value string, limit int) string {
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit])
}
+179
View File
@@ -0,0 +1,179 @@
package audit
import (
"context"
"errors"
"strings"
"testing"
"time"
)
type stubRepo struct {
listFn func(context.Context, string, ListQuery) ([]TurnSummary, error)
getFn func(context.Context, string, string) (TurnDetail, error)
}
func (r *stubRepo) ListTurns(ctx context.Context, tenant string, query ListQuery) ([]TurnSummary, error) {
if r.listFn == nil {
return nil, nil
}
return r.listFn(ctx, tenant, query)
}
func (r *stubRepo) GetTurn(ctx context.Context, tenant, id string) (TurnDetail, error) {
if r.getFn == nil {
return TurnDetail{}, ErrNotFound
}
return r.getFn(ctx, tenant, id)
}
func TestNewServiceRequiresTenantAndRepository(t *testing.T) {
repo := &stubRepo{}
if _, err := NewService("", repo); !errors.Is(err, ErrInvalidArgument) {
t.Fatalf("empty tenant error=%v", err)
}
if _, err := NewService("tenant", nil); !errors.Is(err, ErrInvalidArgument) {
t.Fatalf("nil repository error=%v", err)
}
}
func TestServiceListUsesServerTenantDefaultLimitAndFetchesExtra(t *testing.T) {
var gotTenant string
var gotQuery ListQuery
repo := &stubRepo{listFn: func(_ context.Context, tenant string, query ListQuery) ([]TurnSummary, error) {
gotTenant, gotQuery = tenant, query
return []TurnSummary{}, nil
}}
svc, err := NewService(" tenant-a ", repo)
if err != nil {
t.Fatal(err)
}
page, err := svc.ListTurns(context.Background(), ListTurnsRequest{})
if err != nil {
t.Fatal(err)
}
if gotTenant != "tenant-a" || gotQuery.Limit != 21 {
t.Fatalf("tenant=%q query=%+v", gotTenant, gotQuery)
}
if page.Items == nil || page.NextCursor != "" {
t.Fatalf("page=%+v", page)
}
}
func TestServiceListBuildsStableNextCursor(t *testing.T) {
t3 := time.Date(2026, 7, 21, 3, 0, 0, 0, time.UTC)
t2 := t3.Add(-time.Minute)
t1 := t2.Add(-time.Minute)
repo := &stubRepo{listFn: func(_ context.Context, _ string, query ListQuery) ([]TurnSummary, error) {
if query.Limit != 3 {
t.Fatalf("repository limit=%d want=3", query.Limit)
}
return []TurnSummary{{ID: "turn-3", CreatedAt: t3}, {ID: "turn-2", CreatedAt: t2}, {ID: "turn-1", CreatedAt: t1}}, nil
}}
svc, _ := NewService("tenant", repo)
page, err := svc.ListTurns(context.Background(), ListTurnsRequest{Limit: 2})
if err != nil {
t.Fatal(err)
}
if len(page.Items) != 2 || page.Items[1].ID != "turn-2" || page.NextCursor == "" {
t.Fatalf("page=%+v", page)
}
decoded, err := decodeCursor(page.NextCursor)
if err != nil || decoded.ID != "turn-2" || !decoded.CreatedAt.Equal(t2) {
t.Fatalf("next cursor=%+v err=%v", decoded, err)
}
}
func TestServiceListDecodesCursorForRepository(t *testing.T) {
created := time.Date(2026, 7, 21, 2, 0, 0, 123, time.UTC)
cursor := encodeCursor(created, "turn-before")
repo := &stubRepo{listFn: func(_ context.Context, _ string, query ListQuery) ([]TurnSummary, error) {
if query.BeforeID != "turn-before" || query.BeforeCreatedAt == nil || !query.BeforeCreatedAt.Equal(created) {
t.Fatalf("decoded query=%+v", query)
}
return nil, nil
}}
svc, _ := NewService("tenant", repo)
if _, err := svc.ListTurns(context.Background(), ListTurnsRequest{Cursor: cursor}); err != nil {
t.Fatal(err)
}
}
func TestServiceListValidation(t *testing.T) {
svc, _ := NewService("tenant", &stubRepo{})
for _, tc := range []struct {
name string
req ListTurnsRequest
}{
{name: "negative limit", req: ListTurnsRequest{Limit: -1}},
{name: "too large limit", req: ListTurnsRequest{Limit: 101}},
{name: "bad status", req: ListTurnsRequest{Status: "bogus"}},
{name: "long channel", req: ListTurnsRequest{Channel: strings.Repeat("x", 129)}},
{name: "bad cursor", req: ListTurnsRequest{Cursor: "not-a-cursor"}},
} {
t.Run(tc.name, func(t *testing.T) {
if _, err := svc.ListTurns(context.Background(), tc.req); !errors.Is(err, ErrInvalidArgument) {
t.Fatalf("error=%v", err)
}
})
}
}
func TestServiceListAcceptsMaximumLimitAndFilters(t *testing.T) {
repo := &stubRepo{listFn: func(_ context.Context, _ string, query ListQuery) ([]TurnSummary, error) {
if query.Limit != 101 || query.Channel != "dingtalk" || query.Status != StatusSucceeded {
t.Fatalf("query=%+v", query)
}
return nil, nil
}}
svc, _ := NewService("tenant", repo)
if _, err := svc.ListTurns(context.Background(), ListTurnsRequest{Limit: 100, Channel: " dingtalk ", Status: StatusSucceeded}); err != nil {
t.Fatal(err)
}
}
func TestServiceListTruncatesUnicodeSummariesTo200Runes(t *testing.T) {
long := strings.Repeat("初", 250)
repo := &stubRepo{listFn: func(context.Context, string, ListQuery) ([]TurnSummary, error) {
return []TurnSummary{{ID: "turn", CreatedAt: time.Now(), QuestionSummary: long, AnswerSummary: long}}, nil
}}
svc, _ := NewService("tenant", repo)
page, err := svc.ListTurns(context.Background(), ListTurnsRequest{})
if err != nil {
t.Fatal(err)
}
if len([]rune(page.Items[0].QuestionSummary)) != 200 || len([]rune(page.Items[0].AnswerSummary)) != 200 {
t.Fatalf("summary lengths=%d/%d", len([]rune(page.Items[0].QuestionSummary)), len([]rune(page.Items[0].AnswerSummary)))
}
}
func TestServiceGetUsesServerTenant(t *testing.T) {
var gotTenant, gotID string
repo := &stubRepo{getFn: func(_ context.Context, tenant, id string) (TurnDetail, error) {
gotTenant, gotID = tenant, id
return TurnDetail{ID: id}, nil
}}
svc, _ := NewService("tenant-a", repo)
if _, err := svc.GetTurn(context.Background(), " turn-1 "); err != nil {
t.Fatal(err)
}
if gotTenant != "tenant-a" || gotID != "turn-1" {
t.Fatalf("tenant=%q id=%q", gotTenant, gotID)
}
}
func TestServiceGetValidationAndNotFound(t *testing.T) {
repo := &stubRepo{getFn: func(context.Context, string, string) (TurnDetail, error) {
return TurnDetail{}, ErrNotFound
}}
svc, _ := NewService("tenant", repo)
if _, err := svc.GetTurn(context.Background(), " "); !errors.Is(err, ErrInvalidArgument) {
t.Fatalf("blank id error=%v", err)
}
if _, err := svc.GetTurn(context.Background(), strings.Repeat("x", 129)); !errors.Is(err, ErrInvalidArgument) {
t.Fatalf("long id error=%v", err)
}
if _, err := svc.GetTurn(context.Background(), "missing"); !errors.Is(err, ErrNotFound) {
t.Fatalf("missing error=%v", err)
}
}