fix(dingtalk): 登记钉钉知识库 409 space_registration_conflict —— 归档行占名 + 错误被吞
build / build (push) Successful in 57s
build / build (push) Successful in 57s
现象:点「公司级技术支持知识库」登记,返回 HTTP 409:space_registration_conflict。 根因(真数据取证): - source_connections.name 有唯一约束。这 3 个钉钉来源是**早期路径**登记的 (base_url 为空,id 与 dws 现在推导的确定性 id 不同): sc-18d10ca0… 公司级技术支持知识库 / sc-eaef0ec1… ATOM知识库 / sc-dc7cea1c… 技术诊断部知识沉淀。 - 上一步「去掉来源」只是归档下架,**名字仍占着唯一槽位** ⇒ 重新登记时 INSERT 撞 UNIQUE(name)。 - 处理器把**所有**存储层错误都翻译成同一个 409 space_registration_conflict(真实原因被吞)。 修复: - store:同名的另一行若**已归档** ⇒ 改名腾位(`…(已下架 · <短ID>)`,归档行不显示, 数据与审计一行不动);若**仍在使用** ⇒ ErrDingtalkSpaceNameTaken(绝不悄悄改名)。 同一个登记键解析到别的 root 时:在用中的行报 ErrDingtalkSpaceIdentityConflict; 归档过的行允许就地改写("去掉后再用 dws 重新获取"的语义)。 - httpapi:分类映射 —— space_name_conflict / space_identity_conflict(409 + 可行动 hint), 其余内部故障改回 500 space_registration_failed,不再伪装成冲突。 - web:读一次响应体同时取 error 与 hint,**hint 优先**;补两个新码的中文说明。 验证:真 postgres 集成测试复刻线上形态(旧行占名 + 归档 ⇒ 登记成功、旧行改名保持归档、 内容不丢;同名在用 ⇒ 拒绝;同键换 root 在用 ⇒ 拒绝、归档 ⇒ 就地改写);handler 分类测试 (409/409/500,且不回显内部细节);前端 hint 优先用例;make verify 15/15。
This commit is contained in:
@@ -18,6 +18,8 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
- `index.html` 此前**没有缓存头**,CDN/浏览器按启发式缓存它 ⇒ 页面会一直停在旧构建上(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包)。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`);
|
||||
- 带内容哈希的 `/assets/` 长缓存(`immutable`),但**未命中时先回退到"上一版构建的资源"目录、再 404**(`deploy/legacy-assets` 由部署脚本在每次重建前落盘并只读挂载):CDN/浏览器仍持有旧 `index.html` 时,它引用的旧 JS/CSS 依旧能取到 ⇒ 不会出现"JS 404 白屏"或"CSS 404 只有文字没样式";
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -137,8 +138,22 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_registration_conflict"})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_name_conflict",
|
||||
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
|
||||
})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
|
||||
})
|
||||
return
|
||||
case err != nil:
|
||||
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
// First scan is enqueued right away: the new connection has no catalog
|
||||
|
||||
@@ -3,10 +3,13 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func TestDingtalkSessionProxyRelaysSidecarStates(t *testing.T) {
|
||||
@@ -92,3 +95,62 @@ func TestDingtalkSessionUnavailableWithoutSidecar(t *testing.T) {
|
||||
t.Fatalf("sidecar down status = %d, want 503", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记失败必须能被分类:同名来源仍在用 / 同键换空间 是两种不同的冲突,
|
||||
// 数据库内部故障不能伪装成"冲突"(否则线上只能看到一个无细节的 409)。
|
||||
type fakeDingtalkRegistrar struct {
|
||||
*fakeJobStore
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeDingtalkRegistrar) RegisterDingtalkSpace(ctx context.Context, in postgresstore.RegisterDingtalkSpaceInput) (string, error) {
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
return in.ConnectionID(), nil
|
||||
}
|
||||
|
||||
func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
|
||||
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == "/spaces/add" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"key": "support-kb", "name": "公司级技术支持知识库", "root": "root-support"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer sidecar.Close()
|
||||
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
|
||||
|
||||
call := func(storeErr error) (int, string) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
|
||||
handler, err := NewHandler(Config{Store: store})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/9JOK9EEOMLMWX4Q"}`))
|
||||
request.Header.Set("X-Governance-Action", "dingtalk-space")
|
||||
request.Header.Set("Idempotency-Key", "op-dingtalk-register")
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder.Code, recorder.Body.String()
|
||||
}
|
||||
|
||||
status, body := call(postgresstore.ErrDingtalkSpaceNameTaken)
|
||||
if status != http.StatusConflict || !strings.Contains(body, "space_name_conflict") || !strings.Contains(body, "去掉来源") {
|
||||
t.Fatalf("同名冲突 = %d %s", status, body)
|
||||
}
|
||||
status, body = call(postgresstore.ErrDingtalkSpaceIdentityConflict)
|
||||
if status != http.StatusConflict || !strings.Contains(body, "space_identity_conflict") {
|
||||
t.Fatalf("同键冲突 = %d %s", status, body)
|
||||
}
|
||||
status, body = call(errors.New("connection refused: password=hunter2"))
|
||||
if status != http.StatusInternalServerError || !strings.Contains(body, "space_registration_failed") || strings.Contains(body, "hunter2") {
|
||||
t.Fatalf("内部故障 = %d %s(且不得回显细节)", status, body)
|
||||
}
|
||||
// 正常路径仍然成功(别把好的也拦掉)。
|
||||
status, body = call(nil)
|
||||
if status != http.StatusCreated || !strings.Contains(body, "connection_id") {
|
||||
t.Fatalf("正常登记 = %d %s", status, body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ import (
|
||||
// begin only after an admin sets an interval — same posture as the existing
|
||||
// imported DingTalk sources.
|
||||
|
||||
// 登记失败的可行动分类(处理器据此返回不同错误码,前端才能说清"该怎么办"):
|
||||
// - 同名来源**仍在使用**(未归档):不能悄悄改名,也不能出现两个同名来源;
|
||||
// - 同一个登记键已指向另一个 root,而那个来源仍在使用。
|
||||
var (
|
||||
ErrDingtalkSpaceNameTaken = errors.New("dingtalk space name is already used by a live connection")
|
||||
ErrDingtalkSpaceIdentityConflict = errors.New("dingtalk space registration: live connection already serves another root")
|
||||
)
|
||||
|
||||
// RegisterDingtalkSpaceInput describes one space resolved by the sidecar.
|
||||
type RegisterDingtalkSpaceInput struct {
|
||||
RootKey string // sidecar inventory key, e.g. "atom" or "space-1f2e3d4c5b"
|
||||
@@ -56,17 +64,42 @@ func (s *Store) RegisterDingtalkSpace(ctx context.Context, in RegisterDingtalkSp
|
||||
}
|
||||
connectionID := in.ConnectionID()
|
||||
var existingName, existingRoot string
|
||||
err := s.db.QueryRow(ctx, `SELECT name, base_url FROM source_connections WHERE id = $1`, connectionID).Scan(&existingName, &existingRoot)
|
||||
var existingArchived bool
|
||||
err := s.db.QueryRow(ctx, `SELECT name, base_url, archived_at IS NOT NULL FROM source_connections WHERE id = $1`, connectionID).
|
||||
Scan(&existingName, &existingRoot, &existingArchived)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
// fresh registration below
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("load dingtalk connection: %w", err)
|
||||
default:
|
||||
// A different space resolved under the same key must not silently
|
||||
// rewrite the existing connection.
|
||||
if !strings.HasPrefix(existingRoot, "spaces/"+in.RootID+"?") {
|
||||
return "", fmt.Errorf("dingtalk space registration: connection %s already serves another root", connectionID)
|
||||
// 同一个键解析到了另一个 root:**在用中**的行不能悄悄改写(可能是两个不同空间
|
||||
// 撞了同一个键);已经归档的行可以就地改写 —— 这正是"去掉来源之后再用 dws
|
||||
// 重新获取"的语义。
|
||||
if !strings.HasPrefix(existingRoot, "spaces/"+in.RootID+"?") && !existingArchived {
|
||||
return "", ErrDingtalkSpaceIdentityConflict
|
||||
}
|
||||
}
|
||||
// 名字有 UNIQUE 约束,而**旧路径登记**的来源(例如早期直接建的钉钉知识库连接,
|
||||
// base_url 为空、id 与 dws 现在推导出的确定性 id 不同)会一直占着这个名字。
|
||||
// 归档行已经不显示在任何页面,就把它改名腾出位置(数据与审计一行不动);
|
||||
// 仍在使用的同名来源则直接报可行动错误,绝不悄悄改名。
|
||||
var nameHolderID string
|
||||
var nameHolderArchived bool
|
||||
err = s.db.QueryRow(ctx, `SELECT id, archived_at IS NOT NULL FROM source_connections WHERE name = $1 AND id <> $2`, in.Name, connectionID).
|
||||
Scan(&nameHolderID, &nameHolderArchived)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("lookup dingtalk connection name: %w", err)
|
||||
default:
|
||||
if !nameHolderArchived {
|
||||
return "", ErrDingtalkSpaceNameTaken
|
||||
}
|
||||
if _, err := s.db.Exec(ctx, `
|
||||
UPDATE source_connections SET name = $2, updated_at = $3, updated_by = $4 WHERE id = $1`,
|
||||
nameHolderID, archivedConnectionName(in.Name, nameHolderID), in.Now.UTC(), "dingtalk-registration"); err != nil {
|
||||
return "", fmt.Errorf("free archived dingtalk name: %w", err)
|
||||
}
|
||||
}
|
||||
// base_url stores a stable, non-secret locator (the root dentry uuid plus
|
||||
@@ -93,3 +126,25 @@ SET name = EXCLUDED.name, base_url = EXCLUDED.base_url,
|
||||
}
|
||||
return connectionID, nil
|
||||
}
|
||||
|
||||
// archivedConnectionName 给"已归档但名字仍占着唯一槽位"的行一个确定性新名字:
|
||||
// 内建短 ID 后缀保证唯一,并按 name 列(255)截断原名。
|
||||
func archivedConnectionName(name, connectionID string) string {
|
||||
suffix := "(已下架 · " + shortConnectionIDSuffix(connectionID) + ")"
|
||||
runes := []rune(name)
|
||||
if limit := 255 - len([]rune(suffix)); len(runes) > limit && limit > 0 {
|
||||
runes = runes[:limit]
|
||||
}
|
||||
return string(runes) + suffix
|
||||
}
|
||||
|
||||
func shortConnectionIDSuffix(connectionID string) string {
|
||||
trimmed := strings.TrimPrefix(connectionID, "sc-")
|
||||
if len(trimmed) > 8 {
|
||||
trimmed = trimmed[:8]
|
||||
}
|
||||
if trimmed == "" {
|
||||
trimmed = "unknown"
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -221,3 +222,111 @@ func TestRegisterDingtalkSpaceRevivesArchivedConnection(t *testing.T) {
|
||||
t.Fatalf("复活状态 = rows:%d archived:%v by:%q", rows, archivedAt, archivedBy)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景复刻(2026-10-14 线上 409 事故):早期路径登记的同名来源被归档后仍占着
|
||||
// UNIQUE(name) 槽位,而它的 id 与 dws 现在推导出的确定性 id 不同 ⇒ 重新登记撞唯一约束。
|
||||
// 期望:归档行被改名腾位(数据与审计不动),新来源按新 id 正常登记。
|
||||
func TestRegisterDingtalkSpaceFreesNameHeldByArchivedLegacyConnection(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("ApplyMigrations() error = %v", err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 10, 14, 5, 0, 0, 0, time.UTC)
|
||||
|
||||
// 旧路径登记的来源:id 与 dws 推导不同、base_url 为空、已归档、名字仍占槽位。
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections (id, source_type, name, base_url, enabled, archived_at, archived_by, created_at, updated_at)
|
||||
VALUES ('sc-18d10ca094c6071d44a32e531359e3b2', 'dingtalk', '公司级技术支持知识库', '', FALSE, $1, 'yaozhanghao', $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_items (id, source_connection_id, stable_external_id, canonical_uri_hash,
|
||||
title, item_type, visibility, visibility_origin, source_change, created_at, updated_at)
|
||||
VALUES ('item-legacy', 'sc-18d10ca094c6071d44a32e531359e3b2', 'ext-legacy', repeat('b', 64), '旧行留下的文档',
|
||||
'file', 'internal', 'configured_scope', 'unchanged', $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
input := RegisterDingtalkSpaceInput{
|
||||
RootKey: "support-kb", Name: "公司级技术支持知识库", SpaceID: "space-support", RootID: "root-support", Now: now,
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatalf("登记被旧归档行挡住:%v", err)
|
||||
}
|
||||
if connectionID == "sc-18d10ca094c6071d44a32e531359e3b2" {
|
||||
t.Fatalf("不该复用没有身份证据的旧行:%s", connectionID)
|
||||
}
|
||||
page, err := store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != connectionID || page.Items[0].Name != "公司级技术支持知识库" {
|
||||
t.Fatalf("列表 = %#v", page.Items)
|
||||
}
|
||||
// 旧行:改名腾位、保持归档、内容一行不丢。
|
||||
var legacyName string
|
||||
var legacyArchivedAt *time.Time
|
||||
var legacyItems int
|
||||
if err := pool.QueryRow(ctx, `SELECT name, archived_at, (SELECT COUNT(*)::int FROM source_items WHERE source_connection_id = 'sc-18d10ca094c6071d44a32e531359e3b2') FROM source_connections WHERE id = 'sc-18d10ca094c6071d44a32e531359e3b2'`).
|
||||
Scan(&legacyName, &legacyArchivedAt, &legacyItems); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if legacyName == "公司级技术支持知识库" || !strings.Contains(legacyName, "(已下架 · 18d10ca0)") {
|
||||
t.Fatalf("旧归档行没有被改名腾位:%q", legacyName)
|
||||
}
|
||||
if legacyArchivedAt == nil || legacyItems != 1 {
|
||||
t.Fatalf("旧归档行被破坏:archived=%v items=%d", legacyArchivedAt, legacyItems)
|
||||
}
|
||||
|
||||
// 同名来源仍在使用(未归档)时:拒绝并给出可行动错误,且不写任何东西。
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections (id, source_type, name, enabled, created_at, updated_at)
|
||||
VALUES ('sc-live-other', 'dingtalk', '在用中的同名来源', TRUE, $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "other-key", Name: "在用中的同名来源", SpaceID: "space-other", RootID: "root-other", Now: now,
|
||||
})
|
||||
if !errors.Is(err, ErrDingtalkSpaceNameTaken) {
|
||||
t.Fatalf("同名在用来源 = %v, want ErrDingtalkSpaceNameTaken", err)
|
||||
}
|
||||
|
||||
// 同一个登记键解析到另一个 root:在用中 ⇒ 拒绝;已归档 ⇒ 就地改写。
|
||||
held := RegisterDingtalkSpaceInput{RootKey: "held-key", Name: "同键来源", SpaceID: "space-a", RootID: "root-a", Now: now}
|
||||
heldID, err := store.RegisterDingtalkSpace(ctx, held)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "held-key", Name: "同键来源", SpaceID: "space-b", RootID: "root-b", Now: now,
|
||||
})
|
||||
if !errors.Is(err, ErrDingtalkSpaceIdentityConflict) {
|
||||
t.Fatalf("同键换 root(在用)= %v, want ErrDingtalkSpaceIdentityConflict", err)
|
||||
}
|
||||
if err := store.ArchiveSourceConnection(ctx, heldID, "yaozhanghao", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "held-key", Name: "同键来源", SpaceID: "space-b", RootID: "root-b", Now: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("归档后同键换 root 应就地改写:%v", err)
|
||||
}
|
||||
var rootAfter string
|
||||
if err := pool.QueryRow(ctx, `SELECT base_url FROM source_connections WHERE id = $1`, heldID).Scan(&rootAfter); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(rootAfter, "spaces/root-b?") {
|
||||
t.Fatalf("归档行没有被就地改写:%q", rootAfter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,17 @@ afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('DingTalk session client', () => {
|
||||
it('returns the starting state immediately while the QR is being generated', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
id: 'session-1', state: 'starting', created_at: 1, expires_at: 2,
|
||||
}), { status: 201 }))
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
id: 'session-1',
|
||||
state: 'starting',
|
||||
created_at: 1,
|
||||
expires_at: 2,
|
||||
}),
|
||||
{ status: 201 }
|
||||
)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const target = 'https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview'
|
||||
@@ -18,14 +26,51 @@ describe('DingTalk session client', () => {
|
||||
})
|
||||
|
||||
it('preserves login_required as a machine-readable error for automatic QR fallback', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
|
||||
JSON.stringify({ error: 'login_required' }),
|
||||
{ status: 409, headers: { 'Content-Type': 'application/json' } },
|
||||
)))
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'login_required' }), {
|
||||
status: 409,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
const error = await registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview')
|
||||
.then(() => null, (cause: unknown) => cause)
|
||||
const error = await registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview').then(
|
||||
() => null,
|
||||
(cause: unknown) => cause
|
||||
)
|
||||
expect(error).toBeInstanceOf(DingtalkRequestError)
|
||||
expect(error).toMatchObject({ code: 'login_required', status: 409 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('钉钉知识库登记的失败说明', () => {
|
||||
it('后端 hint 优先,其次本地文案;错误码始终带出', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'space_name_conflict', hint: '已有同名来源仍在使用:先「去掉来源」' }), {
|
||||
status: 409,
|
||||
})
|
||||
)
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'已有同名来源仍在使用:先「去掉来源」'
|
||||
)
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_identity_conflict' }), { status: 409 }))
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'这个登记键已指向另一个知识库空间'
|
||||
)
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_registration_failed' }), { status: 500 }))
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'登记失败(服务端内部错误)'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
+59
-15
@@ -4,7 +4,8 @@ import { newOperationID } from './operationKey'
|
||||
// The API proxies to the dingtalk-login sidecar; this module never sees the
|
||||
// token itself — only the base64 QR image and a terminal state.
|
||||
|
||||
export type DingtalkSessionState = 'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed'
|
||||
export type DingtalkSessionState =
|
||||
'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed'
|
||||
|
||||
export interface DingtalkSessionView {
|
||||
id: string
|
||||
@@ -15,7 +16,16 @@ export interface DingtalkSessionView {
|
||||
error?: string
|
||||
}
|
||||
|
||||
const sessionStates = new Set<string>(['starting', 'qr', 'scanned', 'reusing', 'success', 'expired', 'failed', 'closed'])
|
||||
const sessionStates = new Set<string>([
|
||||
'starting',
|
||||
'qr',
|
||||
'scanned',
|
||||
'reusing',
|
||||
'success',
|
||||
'expired',
|
||||
'failed',
|
||||
'closed',
|
||||
])
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
@@ -24,7 +34,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
export async function startDingtalkSession(space?: string): Promise<DingtalkSessionView> {
|
||||
const response = await fetch('/api/v1/dingtalk-session', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-session', 'Idempotency-Key': newOperationID() },
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-session',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body: JSON.stringify(space ? { space } : {}),
|
||||
})
|
||||
if (!response.ok) throw new Error(`发起钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
@@ -32,13 +47,19 @@ export async function startDingtalkSession(space?: string): Promise<DingtalkSess
|
||||
}
|
||||
|
||||
export async function fetchDingtalkSession(id: string, signal?: AbortSignal): Promise<DingtalkSessionView> {
|
||||
const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { headers: { Accept: 'application/json' }, signal })
|
||||
const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`读取钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
return parseSession(await response.json())
|
||||
}
|
||||
|
||||
export async function cancelDingtalkSession(id: string): Promise<void> {
|
||||
await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { Accept: 'application/json' } }).catch(() => undefined)
|
||||
await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
|
||||
export interface RegisteredDingtalkSpace {
|
||||
@@ -50,7 +71,7 @@ export class DingtalkRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly code: string,
|
||||
public readonly status: number,
|
||||
public readonly status: number
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'DingtalkRequestError'
|
||||
@@ -63,36 +84,59 @@ export class DingtalkRequestError extends Error {
|
||||
export async function registerDingtalkSpace(url: string): Promise<RegisteredDingtalkSpace> {
|
||||
const response = await fetch('/api/v1/dingtalk-spaces', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-space', 'Idempotency-Key': newOperationID() },
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-space',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
// 响应体只能读一次:错误码与后端 hint 一起取出(hint 优先,它比本地文案更具体)。
|
||||
let code = ''
|
||||
let hint = ''
|
||||
try {
|
||||
const parsed = await response.json() as unknown
|
||||
if (isRecord(parsed) && typeof parsed.error === 'string') code = parsed.error
|
||||
} catch { /* status-only */ }
|
||||
const parsed = (await response.json()) as unknown
|
||||
if (isRecord(parsed)) {
|
||||
if (typeof parsed.error === 'string') code = parsed.error
|
||||
if (typeof parsed.hint === 'string') hint = parsed.hint
|
||||
}
|
||||
} catch {
|
||||
/* status-only */
|
||||
}
|
||||
const friendly: Record<string, string> = {
|
||||
login_required: '钉钉扫码会话无效或已过期,请先在钉钉来源卡片上「扫码刷新会话」',
|
||||
space_not_found: '未找到该知识库空间:请确认空间链接正确且当前账号有阅读权限',
|
||||
name_conflict: '该空间与已登记的来源同名',
|
||||
// 登记冲突分两种:同名来源还在用 vs 同一个登记键指向了别的空间。原因要说清,
|
||||
// 否则用户只能看到一个无细节的 409(2026-10-14 线上就是这样卡住的)。
|
||||
space_name_conflict: '已有同名来源仍在使用(未下架):先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间',
|
||||
space_identity_conflict: '这个登记键已指向另一个知识库空间:刷新列表后重试;仍失败就把该来源「去掉来源」再登记',
|
||||
space_registration_failed: '登记失败(服务端内部错误):已记录,请稍后重试或让管理员看服务日志',
|
||||
invalid_space_url: '链接不是有效的钉钉知识库空间地址(应形如 alidocs.dingtalk.com/i/spaces/…)',
|
||||
}
|
||||
throw new DingtalkRequestError(
|
||||
friendly[code] || `登记钉钉知识库失败(HTTP ${response.status}${code ? ':' + code : ''})`,
|
||||
hint || friendly[code] || `登记钉钉知识库失败(HTTP ${response.status}${code ? ':' + code : ''})`,
|
||||
code,
|
||||
response.status,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
const value = (await response.json()) as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid dingtalk space response')
|
||||
const data = value.data
|
||||
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string') throw new Error('invalid dingtalk space response')
|
||||
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string')
|
||||
throw new Error('invalid dingtalk space response')
|
||||
return { connection_id: data.connection_id, name: data.name }
|
||||
}
|
||||
|
||||
function parseSession(value: unknown): DingtalkSessionView {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || typeof value.state !== 'string' || !sessionStates.has(value.state)) {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
typeof value.id !== 'string' ||
|
||||
typeof value.state !== 'string' ||
|
||||
!sessionStates.has(value.state)
|
||||
) {
|
||||
throw new Error('invalid dingtalk session response')
|
||||
}
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user