cfe3271fa2
The loopback fetch now degrades to the public URL ...
399 lines
13 KiB
Go
399 lines
13 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
|
)
|
|
|
|
const cardImageTestID = "5f0a1c2e-3b4d-5e6f-8a9b-0c1d2e3f4a5b"
|
|
const cardImageTestMediaID = "@lADP-test-media-id"
|
|
|
|
type cardImageTestServer struct {
|
|
server *httptest.Server
|
|
imageBytes []byte
|
|
oversizeBytes []byte
|
|
uploadErrcode int
|
|
|
|
tokenCalls int
|
|
uploadCalls int
|
|
uploadedBytes int
|
|
fetched []string
|
|
|
|
mu sync.Mutex
|
|
uploadedC chan struct{}
|
|
}
|
|
|
|
func newCardImageTestServer(t *testing.T) *cardImageTestServer {
|
|
t.Helper()
|
|
fixture := &cardImageTestServer{
|
|
imageBytes: []byte("\x89PNG\r\n\x1a\nfixture-bytes"),
|
|
oversizeBytes: make([]byte, 512),
|
|
uploadedC: make(chan struct{}, 4),
|
|
}
|
|
mux := http.NewServeMux()
|
|
serveImage := func(w http.ResponseWriter, r *http.Request) {
|
|
fixture.mu.Lock()
|
|
fixture.fetched = append(fixture.fetched, r.URL.Path)
|
|
fixture.mu.Unlock()
|
|
body := fixture.imageBytes
|
|
if strings.HasSuffix(r.URL.Path, "big") {
|
|
body = fixture.oversizeBytes
|
|
}
|
|
w.Header().Set("Content-Type", "image/png")
|
|
_, _ = w.Write(body)
|
|
}
|
|
mux.HandleFunc("/dingtalk/i/", serveImage)
|
|
mux.HandleFunc("/images/", serveImage)
|
|
mux.HandleFunc("/gettoken", func(w http.ResponseWriter, r *http.Request) {
|
|
fixture.mu.Lock()
|
|
fixture.tokenCalls++
|
|
fixture.mu.Unlock()
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"errcode": 0, "errmsg": "ok", "access_token": "test-token", "expires_in": 7200,
|
|
})
|
|
})
|
|
mux.HandleFunc("/media/upload", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Query().Get("access_token") != "test-token" || r.URL.Query().Get("type") != "image" {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"errcode": 40001, "errmsg": "bad token"})
|
|
return
|
|
}
|
|
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
file, _, err := r.FormFile("media")
|
|
if err == nil {
|
|
data, _ := io.ReadAll(file)
|
|
_ = file.Close()
|
|
fixture.mu.Lock()
|
|
fixture.uploadedBytes += len(data)
|
|
fixture.mu.Unlock()
|
|
}
|
|
fixture.mu.Lock()
|
|
fixture.uploadCalls++
|
|
code := fixture.uploadErrcode
|
|
fixture.mu.Unlock()
|
|
select {
|
|
case fixture.uploadedC <- struct{}{}:
|
|
default:
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"errcode": code, "errmsg": "ok", "media_id": cardImageTestMediaID,
|
|
})
|
|
})
|
|
fixture.server = httptest.NewServer(mux)
|
|
t.Cleanup(fixture.server.Close)
|
|
return fixture
|
|
}
|
|
|
|
func (f *cardImageTestServer) resolver(t *testing.T, mutate func(*CardImageMediaOptions)) CardImageMediaRewriter {
|
|
t.Helper()
|
|
opts := CardImageMediaOptions{
|
|
ClientID: "robot-client-id",
|
|
ClientSecret: "robot-client-secret",
|
|
ImageURLPrefix: f.server.URL + "/dingtalk/i/",
|
|
TokenURL: f.server.URL + "/gettoken",
|
|
UploadURL: f.server.URL + "/media/upload",
|
|
HTTPClient: f.server.Client(),
|
|
}
|
|
if mutate != nil {
|
|
mutate(&opts)
|
|
}
|
|
rewriter, err := NewCardImageMediaRewriter(opts)
|
|
if err != nil {
|
|
t.Fatalf("NewCardImageMediaRewriter: %v", err)
|
|
}
|
|
if rewriter == nil {
|
|
t.Fatal("expected a configured rewriter")
|
|
}
|
|
return rewriter
|
|
}
|
|
|
|
func (f *cardImageTestServer) counts() (token, upload int) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.tokenCalls, f.uploadCalls
|
|
}
|
|
|
|
func (f *cardImageTestServer) uploadedByteCount() int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.uploadedBytes
|
|
}
|
|
|
|
func (f *cardImageTestServer) imageURL(id string) string {
|
|
return f.server.URL + "/dingtalk/i/" + id
|
|
}
|
|
|
|
func (f *cardImageTestServer) waitForUpload(t *testing.T) {
|
|
t.Helper()
|
|
select {
|
|
case <-f.uploadedC:
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("timed out waiting for the media upload")
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaRewritesOwnImageAndCachesMediaID(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
content := fmt.Sprintf("看图:", fixture.imageURL(cardImageTestID))
|
|
|
|
got := rewriter.RewriteForCard(context.Background(), content, true)
|
|
want := fmt.Sprintf("看图:", cardImageTestMediaID)
|
|
if got != want {
|
|
t.Fatalf("got=%q want=%q", got, want)
|
|
}
|
|
if _, uploads := fixture.counts(); uploads != 1 {
|
|
t.Fatalf("uploads=%d want 1", uploads)
|
|
}
|
|
if got := fixture.uploadedByteCount(); got != len(fixture.imageBytes) {
|
|
t.Fatalf("uploaded bytes=%d want %d", got, len(fixture.imageBytes))
|
|
}
|
|
|
|
// A second rewrite must reuse the cached media id without another upload,
|
|
// and the token must only be fetched once.
|
|
again := rewriter.RewriteForCard(context.Background(), content, true)
|
|
if again != want {
|
|
t.Fatalf("cached rewrite got=%q want=%q", again, want)
|
|
}
|
|
tokens, uploads := fixture.counts()
|
|
if uploads != 1 || tokens != 1 {
|
|
t.Fatalf("tokens=%d uploads=%d want 1/1", tokens, uploads)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaPartialFramesNeverBlockAndPickUpLater(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
content := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
// A streaming frame keeps the external URL but starts the upload.
|
|
if got := rewriter.RewriteForCard(context.Background(), content, false); got != content {
|
|
t.Fatalf("streaming frame must stay unchanged, got=%q", got)
|
|
}
|
|
fixture.waitForUpload(t)
|
|
|
|
deadline := time.Now().Add(2 * time.Second)
|
|
for {
|
|
got := rewriter.RewriteForCard(context.Background(), content, false)
|
|
if strings.Contains(got, cardImageTestMediaID) {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("media id never became available, got=%q", got)
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
if _, uploads := fixture.counts(); uploads != 1 {
|
|
t.Fatalf("uploads=%d want 1", uploads)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaIgnoresForeignAndIncompleteReferences(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
content := strings.Join([]string{
|
|
fmt.Sprintf("", cardImageTestID),
|
|
fmt.Sprintf("", fixture.imageURL("not-a-stable-id")),
|
|
fmt.Sprintf("),
|
|
fmt.Sprintf("纯链接 %s", fixture.imageURL(cardImageTestID)),
|
|
}, "\n")
|
|
|
|
if got := rewriter.RewriteForCard(context.Background(), content, true); got != content {
|
|
t.Fatalf("content must be untouched, got=%q", got)
|
|
}
|
|
tokens, uploads := fixture.counts()
|
|
if tokens != 0 || uploads != 0 {
|
|
t.Fatalf("tokens=%d uploads=%d want 0/0", tokens, uploads)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaFallsBackWhenUploadFails(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
fixture.uploadErrcode = 40035
|
|
rewriter := fixture.resolver(t, nil)
|
|
content := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
if got := rewriter.RewriteForCard(context.Background(), content, true); got != content {
|
|
t.Fatalf("failed upload must keep the external reference, got=%q", got)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaFallsBackForOversizeImages(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, func(opts *CardImageMediaOptions) {
|
|
opts.MaxBytes = 128
|
|
})
|
|
content := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
if got := rewriter.RewriteForCard(context.Background(), content, true); got != content {
|
|
t.Fatalf("oversize image must keep the external reference, got=%q", got)
|
|
}
|
|
if _, uploads := fixture.counts(); uploads != 0 {
|
|
t.Fatalf("uploads=%d want 0", uploads)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaFetchUsesLoopbackPrefix(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, func(opts *CardImageMediaOptions) {
|
|
opts.ImageURLPrefix = "https://weknora-api.invalid/dingtalk/i/"
|
|
opts.FetchURLPrefix = fixture.server.URL + "/images/"
|
|
})
|
|
content := fmt.Sprintf("", cardImageTestID)
|
|
|
|
got := rewriter.RewriteForCard(context.Background(), content, true)
|
|
if !strings.Contains(got, cardImageTestMediaID) {
|
|
t.Fatalf("loopback fetch must still produce a media id, got=%q", got)
|
|
}
|
|
fixture.mu.Lock()
|
|
defer fixture.mu.Unlock()
|
|
if len(fixture.fetched) != 1 || !strings.HasPrefix(fixture.fetched[0], "/images/") {
|
|
t.Fatalf("fetched=%v want one loopback path", fixture.fetched)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaDeduplicatesConcurrentUploads(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
content := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 4; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
rewriter.RewriteForCard(context.Background(), content, true)
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
if _, uploads := fixture.counts(); uploads != 1 {
|
|
t.Fatalf("uploads=%d want 1 for concurrent callers", uploads)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaRewriterRequiresFullConfiguration(t *testing.T) {
|
|
for name, opts := range map[string]CardImageMediaOptions{
|
|
"missing client id": {ClientSecret: "s", ImageURLPrefix: "https://img.example/dingtalk/i/"},
|
|
"missing secret": {ClientID: "id", ImageURLPrefix: "https://img.example/dingtalk/i/"},
|
|
"missing prefix": {ClientID: "id", ClientSecret: "s"},
|
|
} {
|
|
rewriter, err := NewCardImageMediaRewriter(opts)
|
|
if err != nil || rewriter != nil {
|
|
t.Fatalf("%s: rewriter=%v err=%v want nil/nil", name, rewriter, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestStreamingCardDeliverySendsMediaIDAndKeepsMarkdownExternal(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
answer := fmt.Sprintf("CR20V 接线如下:\n\n", fixture.imageURL(cardImageTestID))
|
|
|
|
card := &fakeStreamingCard{startID: "track-image-card"}
|
|
qa := &fakeStreamingQA{chunks: []string{answer}, result: core.QAResult{Answer: answer}}
|
|
reply := &fakeReply{}
|
|
h := newTestHandlerWithStreaming(t, qa, reply, card)
|
|
h.cardImageMedia = rewriter
|
|
|
|
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
|
t.Fatalf("Handle: %v", err)
|
|
}
|
|
if len(card.updates) == 0 {
|
|
t.Fatal("no card update was recorded")
|
|
}
|
|
final := card.updates[len(card.updates)-1]
|
|
if !final.isFinalize {
|
|
t.Fatalf("last update must finalize the card, got %+v", final)
|
|
}
|
|
if !strings.Contains(final.content, cardImageTestMediaID) {
|
|
t.Fatalf("final card body must carry the media id, got=%q", final.content)
|
|
}
|
|
if strings.Contains(final.content, fixture.server.URL) {
|
|
t.Fatalf("final card body must not keep the external URL, got=%q", final.content)
|
|
}
|
|
}
|
|
|
|
func TestCardFinalizeFallbackKeepsExternalImageURL(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, nil)
|
|
answer := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
card := &fakeStreamingCard{startID: "track-image-fallback", updateErr: errors.New("card unavailable")}
|
|
qa := &fakeStreamingQA{chunks: []string{answer}, result: core.QAResult{Answer: answer}}
|
|
reply := &fakeReply{}
|
|
h := newTestHandlerWithStreaming(t, qa, reply, card)
|
|
h.cardImageMedia = rewriter
|
|
|
|
if err := h.Handle(context.Background(), directTextCallback()); err != nil {
|
|
t.Fatalf("Handle: %v", err)
|
|
}
|
|
if !reply.called {
|
|
t.Fatal("markdown fallback was not sent")
|
|
}
|
|
if !strings.Contains(reply.lastText, fixture.server.URL) {
|
|
t.Fatalf("markdown fallback must keep the external URL, got=%q", reply.lastText)
|
|
}
|
|
if strings.Contains(reply.lastText, cardImageTestMediaID) {
|
|
t.Fatalf("markdown fallback must not carry a media id, got=%q", reply.lastText)
|
|
}
|
|
}
|
|
|
|
func TestCardImageMediaFallsBackToPublicURLWhenLoopbackMisses(t *testing.T) {
|
|
fixture := newCardImageTestServer(t)
|
|
rewriter := fixture.resolver(t, func(opts *CardImageMediaOptions) {
|
|
// The loopback route exists but does not serve this object.
|
|
opts.FetchURLPrefix = fixture.server.URL + "/missing/"
|
|
})
|
|
content := fmt.Sprintf("", fixture.imageURL(cardImageTestID))
|
|
|
|
got := rewriter.RewriteForCard(context.Background(), content, true)
|
|
if !strings.Contains(got, cardImageTestMediaID) {
|
|
t.Fatalf("public fallback must still produce a media id, got=%q", got)
|
|
}
|
|
fixture.mu.Lock()
|
|
defer fixture.mu.Unlock()
|
|
if len(fixture.fetched) != 1 || !strings.HasPrefix(fixture.fetched[0], "/dingtalk/i/") {
|
|
t.Fatalf("fetched=%v want a single public fetch after the loopback miss", fixture.fetched)
|
|
}
|
|
}
|
|
|
|
func TestCardImageRefCountsSplitMediaAndExternalReferences(t *testing.T) {
|
|
content := strings.Join([]string{
|
|
fmt.Sprintf("", cardImageTestMediaID),
|
|
fmt.Sprintf("", cardImageTestID),
|
|
fmt.Sprintf("", cardImageTestMediaID),
|
|
}, "\n")
|
|
total, external, media := cardImageRefCounts(content)
|
|
if total != 3 || external != 1 || media != 2 {
|
|
t.Fatalf("total=%d external=%d media=%d want 3/1/2", total, external, media)
|
|
}
|
|
if total, external, media := cardImageRefCounts("无图回答"); total != 0 || external != 0 || media != 0 {
|
|
t.Fatalf("plain text must report no image refs, got %d/%d/%d", total, external, media)
|
|
}
|
|
}
|
|
|
|
func TestCardUpdateDiagnosticReportsImageReferenceShape(t *testing.T) {
|
|
content := fmt.Sprintf("正文\n\n", cardImageTestMediaID)
|
|
got := formatCardUpdateDiagnostic(content, true, false)
|
|
if !strings.Contains(got, "image_refs=1") || !strings.Contains(got, "media_image_refs=1") || !strings.Contains(got, "external_image_refs=0") {
|
|
t.Fatalf("diagnostic must report image reference shape: %q", got)
|
|
}
|
|
if strings.Contains(got, cardImageTestMediaID) {
|
|
t.Fatalf("diagnostic must not leak the media id: %q", got)
|
|
}
|
|
}
|