Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56b8cabed9 | |||
| cc4906b6a9 |
@@ -10,6 +10,17 @@ DOBOTAI_OPS_QUERY_TIMEOUT=4s
|
||||
DOBOTAI_OPS_MAX_CONNS=2
|
||||
DOBOTAI_OPS_MIN_CONNS=0
|
||||
|
||||
# API and worker share this opt-in binding; no browser-selected paths/credentials.
|
||||
# Runtime root is the read-only existing weekly_report directory (SDK/config and
|
||||
# private secret file). Python must be compatible and already provide PyYAML.
|
||||
# Container deployment requires approved runtime/script mounts; not auto-installed.
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m
|
||||
|
||||
APP_ADDR=:8080
|
||||
DATABASE_URL=postgres://governance@postgres:5432/governance?sslmode=disable
|
||||
PGPASSFILE=/run/secrets/pgpass
|
||||
|
||||
+5
-3
@@ -4,11 +4,13 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;网页触发的后台同步队列及问答组织关联尚未接入。
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是实时通讯录同步或使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。
|
||||
- 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。
|
||||
- **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
- 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。
|
||||
|
||||
@@ -44,6 +44,10 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/v1/qa-ops/organization/sync": {
|
||||
"get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}},
|
||||
"post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}}
|
||||
},
|
||||
"/api/v1/qa-ops/organization": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
@@ -95,6 +99,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}},
|
||||
"/api/v1/qa-ops/status": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
|
||||
+12
-1
@@ -133,8 +133,19 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if qaSettings.Problem != "" {
|
||||
log.Print("QA operations source is unavailable; governance remains online")
|
||||
}
|
||||
qaOrganizationStore := qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
qaSyncSettings, qaSyncErr := qaopsorg.LoadSyncSettings(getenv)
|
||||
if qaSyncErr != nil {
|
||||
log.Print("QA directory synchronization is not configured; governance remains online")
|
||||
}
|
||||
var qaSyncStore httpapi.QAOrgSyncStore
|
||||
if getenv("DOBOTAI_OPS_TENANT_KEY") != "" {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAOrg: qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY")),
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
QAOrg: qaOrganizationStore,
|
||||
QAOps: qaReader,
|
||||
QAOpsTenantKey: qaSettings.TenantKey,
|
||||
QAOpsEnabled: qaSettings.Enabled,
|
||||
|
||||
@@ -53,6 +53,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func configureDirectorySync(pool *pgxpool.Pool, getenv func(string) string, handlers map[string]jobs.Handler) error {
|
||||
settings, err := qaopsorg.LoadSyncSettings(getenv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !settings.Enabled {
|
||||
return nil
|
||||
}
|
||||
if err = settings.CheckWorkerRuntime(); err != nil {
|
||||
return err
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, settings.Tenant)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleDirectorySync(ctx, job, settings.Runner)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectorySyncWorkerRegistrationIsOptInAndRuntimeChecked(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled sync registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED"] = "true"
|
||||
if err := configureDirectorySync(nil, get, handlers); err == nil {
|
||||
t.Fatal("incomplete binding registered")
|
||||
}
|
||||
root := t.TempDir()
|
||||
script := filepath.Join(root, "fixture.py")
|
||||
if err := os.WriteFile(script, []byte("# fixture; not executed by registration"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-tenant"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"] = "/bin/sh"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = script
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"] = root
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"] = root
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || handlers[qaopsorg.NewStore(nil, "fixture-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("configured worker was not wired")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = filepath.Join(root, "missing.py")
|
||||
if err := configureDirectorySync(nil, get, map[string]jobs.Handler{}); err == nil {
|
||||
t.Fatal("missing runtime advertised as ready")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Actor keys are internal join material, never fields of the browser response.
|
||||
type ActorIdentity struct {
|
||||
ActorID string `json:"actor_id"`
|
||||
StaffID string `json:"staff_id"`
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
SyncedAt *time.Time `json:"synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
Basis string `json:"basis"`
|
||||
}
|
||||
type RecordOrganization struct {
|
||||
Version OrganizationVersion `json:"version"`
|
||||
State string `json:"state"`
|
||||
Departments []string `json:"departments"`
|
||||
Region string `json:"region"`
|
||||
SourceDepartment string `json:"source_department"`
|
||||
SourceRegion string `json:"source_region"`
|
||||
DepartmentOrigin string `json:"department_origin"`
|
||||
RegionOrigin string `json:"region_origin"`
|
||||
}
|
||||
type UsageGroup struct {
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Total int64
|
||||
Succeeded int64
|
||||
Failed int64
|
||||
}
|
||||
type UsageGroups struct {
|
||||
Groups []UsageGroup `json:"-"`
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func decodeRecord(raw string) (Record, error) {
|
||||
var wire struct {
|
||||
Record
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &wire); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
wire.Record.Identity = wire.Identity
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return UsageGroups{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return UsageGroups{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, patternErr := recordKeywordPattern(query.Keyword)
|
||||
if patternErr != nil {
|
||||
return UsageGroups{}, patternErr
|
||||
}
|
||||
result := UsageGroups{Groups: []UsageGroup{}}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var group UsageGroup
|
||||
if rows.Scan(&raw, &group.Total, &group.Succeeded, &group.Failed) != nil || json.Unmarshal([]byte(raw), &group.Identity) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
result.Groups = append(result.Groups, group)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Keep the agreed field ordering after governance enriches an initially empty column.
|
||||
func AddRecordColumns(page *RecordPage, extra ...string) {
|
||||
all := map[string]bool{}
|
||||
for _, col := range append(page.Columns, extra...) {
|
||||
all[col] = true
|
||||
}
|
||||
page.Columns = []string{}
|
||||
for _, col := range recordColumnOrder {
|
||||
if all[col] {
|
||||
page.Columns = append(page.Columns, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
dsn := qaRecordsFixture(t, pool)
|
||||
execFixture(t, pool, `UPDATE messages SET actor_union_id_snapshot='fixture-union' WHERE id='msg-req-3'`, `UPDATE messages SET actor_id=NULL WHERE id='msg-req-4'`)
|
||||
client := buildReadOnlyClient(t, dsn)
|
||||
query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}, Limit: 1}
|
||||
page, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Total != 4 || len(page.Items) != 1 || page.Items[0].Identity.StaffID != "" {
|
||||
t.Fatal("fixture first page should be anonymous")
|
||||
}
|
||||
found := false
|
||||
for _, actor := range page.ScopeActors {
|
||||
if actor.StaffID == "ext-actor-1" && actor.UnionID == "fixture-union" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("whole-filter keys missing; later-page department would be hidden")
|
||||
}
|
||||
item, err := client.GetRecord(context.Background(), "default", "turn-3")
|
||||
if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" {
|
||||
t.Fatalf("stable identity not read from inbound actor/message: %v", err)
|
||||
}
|
||||
raw, _ := json.Marshal(page)
|
||||
detail, _ := json.Marshal(item)
|
||||
for _, s := range []string{string(raw), string(detail)} {
|
||||
for _, private := range []string{"ext-actor-1", "fixture-union", "actor-row-1", "_identity", "scope_actors"} {
|
||||
if strings.Contains(s, private) {
|
||||
t.Fatal("internal roster key leaked into API JSON")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAUsageGroupsCountEventsOnceOverTheFullFilter(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
dsn := qaRecordsFixture(t, pool)
|
||||
|
||||
client := buildReadOnlyClient(t, dsn)
|
||||
query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}}
|
||||
result, err := client.ReadUsageGroups(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var total, success, failed int64
|
||||
for _, g := range result.Groups {
|
||||
total += g.Total
|
||||
success += g.Succeeded
|
||||
failed += g.Failed
|
||||
}
|
||||
if total != 4 || success != 3 || failed != 1 || result.AsOf.IsZero() {
|
||||
t.Fatalf("events multiplied/foreign tenant included: %d %d %d", total, success, failed)
|
||||
}
|
||||
query.Keyword = "%"
|
||||
result, err = client.ReadUsageGroups(context.Background(), query)
|
||||
if err != nil || len(result.Groups) != 0 {
|
||||
t.Fatal("usage keyword wildcard not literal")
|
||||
}
|
||||
}
|
||||
@@ -51,21 +51,23 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
@@ -76,12 +78,14 @@ type RecordQuery struct {
|
||||
}
|
||||
|
||||
type RecordPage struct {
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
}
|
||||
|
||||
type recordCursor struct {
|
||||
@@ -92,10 +96,12 @@ type recordCursor struct {
|
||||
|
||||
// A single inbound-message join controls names/time. Feedback is preaggregated;
|
||||
// joining each feedback row directly would multiply the business event count.
|
||||
const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))`
|
||||
const recordsBaseSQL = `
|
||||
WITH records AS (
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,
|
||||
jsonb_build_object(
|
||||
'_identity',` + actorIdentitySQL + `,
|
||||
'id',t.id,'status',t.status,'question',t.question,'answer',t.answer,
|
||||
'asked_at',COALESCE(m.created_at,t.created_at),
|
||||
'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END,
|
||||
@@ -137,15 +143,25 @@ const recordColumnsSQL = `SELECT count(*),jsonb_build_object(
|
||||
'region',COALESCE(bool_or(payload->>'region'<>''),false),
|
||||
'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR
|
||||
(payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false)
|
||||
)::text FROM records WHERE `
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text FROM records WHERE `
|
||||
|
||||
var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
|
||||
func recordKeywordPattern(keyword string) (string, error) {
|
||||
if !utf8.ValidString(keyword) || utf8.RuneCountInString(keyword) > 200 || strings.ContainsRune(keyword, 0) {
|
||||
return "", ErrInvalidQuery
|
||||
}
|
||||
if keyword == "" {
|
||||
return "", nil
|
||||
}
|
||||
return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil
|
||||
}
|
||||
|
||||
func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > 100 || !utf8.ValidString(query.Keyword) || utf8.RuneCountInString(query.Keyword) > 200 || strings.ContainsRune(query.Keyword, 0) || len(query.Cursor) > 2048 {
|
||||
if query.Limit < 1 || query.Limit > 100 || len(query.Cursor) > 2048 {
|
||||
return RecordPage{}, fmt.Errorf("%w: invalid record filters", ErrInvalidQuery)
|
||||
}
|
||||
scopeBytes, _ := json.Marshal([]string{query.Window.TenantKey, query.Window.Start.UTC().Format(time.RFC3339Nano), query.Window.End.UTC().Format(time.RFC3339Nano), query.Keyword})
|
||||
@@ -160,9 +176,9 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
}
|
||||
before = cursor.AskedAt
|
||||
}
|
||||
pattern := ""
|
||||
if query.Keyword != "" {
|
||||
pattern = "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(query.Keyword) + "%"
|
||||
pattern, patternErr := recordKeywordPattern(query.Keyword)
|
||||
if patternErr != nil {
|
||||
return RecordPage{}, patternErr
|
||||
}
|
||||
args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern}
|
||||
page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)}
|
||||
@@ -170,11 +186,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns); err != nil {
|
||||
var rawColumns, rawActors string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
var available map[string]bool
|
||||
if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if err := json.Unmarshal([]byte(rawColumns), &available); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -194,11 +213,11 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var item Record
|
||||
if err := json.Unmarshal([]byte(raw), &item); err != nil {
|
||||
item, err := decodeRecord(raw)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
item.Coverage = CheckAnswerCoverage(item.Answer)
|
||||
|
||||
page.Items = append(page.Items, item)
|
||||
}
|
||||
return rows.Err()
|
||||
@@ -233,10 +252,11 @@ func (c *Client) GetRecord(ctx context.Context, tenantKey, id string) (Record, e
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &item); err != nil {
|
||||
item, err = decodeRecord(raw)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
item.Coverage = CheckAnswerCoverage(item.Answer)
|
||||
|
||||
return nil
|
||||
})
|
||||
return item, err
|
||||
|
||||
@@ -14,6 +14,7 @@ func qaRecordsFixture(t *testing.T, pool *pgxpool.Pool) string {
|
||||
dsn := buildFixture(t, pool)
|
||||
execFixture(t, pool,
|
||||
`ALTER TABLE messages ADD COLUMN actor_name_snapshot text NOT NULL DEFAULT '', ADD COLUMN trigger_person_snapshot text NOT NULL DEFAULT '', ADD COLUMN media_json jsonb NOT NULL DEFAULT '[]'`,
|
||||
`DROP TABLE IF EXISTS answer_feedback`,
|
||||
`CREATE TABLE answer_feedback(id text PRIMARY KEY,tenant_key text,channel text,turn_id text,answer_message_id text,actor_id text,value text)`,
|
||||
`GRANT SELECT ON answer_feedback TO kg_ro_fixture`,
|
||||
`UPDATE messages SET actor_name_snapshot='测试人员',trigger_person_snapshot='回调昵称' WHERE id='msg-req-3'`,
|
||||
|
||||
@@ -84,7 +84,7 @@ func buildFixture(t *testing.T, pool *pgxpool.Pool) string {
|
||||
question text NOT NULL DEFAULT '', answer text NOT NULL DEFAULT '', error_message text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL)`,
|
||||
`CREATE TABLE messages (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL, actor_id text,
|
||||
department_snapshot text NOT NULL DEFAULT '', region_snapshot text NOT NULL DEFAULT '',
|
||||
department_snapshot text NOT NULL DEFAULT '', region_snapshot text NOT NULL DEFAULT '', actor_union_id_snapshot text NOT NULL DEFAULT '',
|
||||
direction text NOT NULL DEFAULT '', role text NOT NULL DEFAULT '', message_type text NOT NULL DEFAULT '',
|
||||
status text NOT NULL DEFAULT '', text_content text NOT NULL DEFAULT '', created_at timestamptz NOT NULL)`,
|
||||
`CREATE TABLE coverage_decisions (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL,
|
||||
|
||||
@@ -31,7 +31,7 @@ WITH relations AS (
|
||||
('turns','references_json','jsonb'),('turns','knowledge_searched','bool'),
|
||||
('turns','request_message_id','text'),('turns','answer_message_id','text'),
|
||||
('messages','id','text'),('messages','actor_id','text'),('messages','department_snapshot','text'),
|
||||
('messages','region_snapshot','text'),('channel_actors','id','text'),('channel_actors','external_actor_id','text'),
|
||||
('messages','region_snapshot','text'),('messages','actor_union_id_snapshot','text'),('channel_actors','id','text'),('channel_actors','external_actor_id','text'),
|
||||
('coverage_decisions','turn_id','text'),('coverage_decisions','verdict','text')
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
|
||||
if !ok || schema["type"] != "string" || schema["minLength"] != float64(1) || schema["maxLength"] != float64(128) {
|
||||
t.Fatalf("IdempotencyKey header schema is unsafe: %#v", parameter["schema"])
|
||||
}
|
||||
for _, path := range []string{"/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
for _, path := range []string{"/api/v1/qa-ops/organization/sync", "/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
operation, ok := document.Paths[path]["post"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing POST %s", path)
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errQAOrganization = errors.New("organization attribution unavailable")
|
||||
|
||||
type qaAttributionProvider interface {
|
||||
GetAttribution(context.Context) (*qaopsorg.Attribution, error)
|
||||
}
|
||||
|
||||
func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attribution, error) {
|
||||
if config.QAOrg == nil {
|
||||
return qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{})
|
||||
}
|
||||
provider, ok := config.QAOrg.(qaAttributionProvider)
|
||||
if !ok {
|
||||
return nil, errQAOrganization
|
||||
}
|
||||
p, err := provider.GetAttribution(ctx)
|
||||
if err != nil || p == nil {
|
||||
return nil, errQAOrganization
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory"}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
o := &dobotaiops.RecordOrganization{Version: attributionVersion(p), State: person.State, Departments: person.Departments, Region: person.Region, SourceDepartment: item.Department, SourceRegion: item.Region, DepartmentOrigin: "unavailable", RegionOrigin: "unavailable"}
|
||||
if item.Department != "" {
|
||||
o.DepartmentOrigin = "source_snapshot"
|
||||
} else if len(person.Departments) > 0 {
|
||||
item.Department = strings.Join(person.Departments, ";")
|
||||
o.DepartmentOrigin = "current_directory"
|
||||
}
|
||||
if item.Region != "" {
|
||||
o.RegionOrigin = "source_snapshot"
|
||||
} else if person.Region != "" {
|
||||
item.Region = person.Region
|
||||
o.RegionOrigin = "current_directory"
|
||||
}
|
||||
item.Organization = o
|
||||
}
|
||||
func enrichQAPage(page *dobotaiops.RecordPage, p *qaopsorg.Attribution) {
|
||||
version := attributionVersion(p)
|
||||
page.Organization = &version
|
||||
for i := range page.Items {
|
||||
enrichQARecord(&page.Items[i], p)
|
||||
}
|
||||
for _, actor := range page.ScopeActors {
|
||||
person := p.Resolve(actor.StaffID, actor.UnionID)
|
||||
if len(person.Departments) > 0 {
|
||||
dobotaiops.AddRecordColumns(page, "department")
|
||||
}
|
||||
if person.Region != "" {
|
||||
dobotaiops.AddRecordColumns(page, "region")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type qaUsageReader interface {
|
||||
ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error)
|
||||
}
|
||||
type qaUsageRow struct {
|
||||
Key string `json:"key"`
|
||||
Questions int64 `json:"questions"`
|
||||
Succeeded int64 `json:"succeeded"`
|
||||
Failed int64 `json:"failed"`
|
||||
Other int64 `json:"other"`
|
||||
Users *int `json:"users"`
|
||||
RosterPeople *int `json:"roster_people"`
|
||||
}
|
||||
type qaUsage struct {
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Questions int64 `json:"questions"`
|
||||
IdentifiedUsers int `json:"identified_users"`
|
||||
Rows []qaUsageRow `json:"rows"`
|
||||
}
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
for _, key := range keys {
|
||||
row := &qaUsageRow{Key: key}
|
||||
if p.Metadata.State == "ready" {
|
||||
var n int
|
||||
valid := true
|
||||
switch key {
|
||||
case "unassigned":
|
||||
n = p.Metadata.View.UnassignedPeople
|
||||
case "cross_region":
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
row.RosterPeople = &n
|
||||
row.Users = new(int)
|
||||
}
|
||||
}
|
||||
rows[key] = row
|
||||
members[key] = map[string]bool{}
|
||||
}
|
||||
for _, group := range groups.Groups {
|
||||
person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID)
|
||||
key := person.State
|
||||
if person.Region != "" {
|
||||
key = person.Region
|
||||
}
|
||||
row := rows[key]
|
||||
if row == nil {
|
||||
continue
|
||||
}
|
||||
row.Questions += group.Total
|
||||
row.Succeeded += group.Succeeded
|
||||
row.Failed += group.Failed
|
||||
row.Other += group.Total - group.Succeeded - group.Failed
|
||||
result.Questions += group.Total
|
||||
if person.PersonID != "" {
|
||||
members[key][person.PersonID] = true
|
||||
all[person.PersonID] = true
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
row := rows[key]
|
||||
if row.Users != nil {
|
||||
*row.Users = len(members[key])
|
||||
}
|
||||
result.Rows = append(result.Rows, *row)
|
||||
}
|
||||
result.IdentifiedUsers = len(all)
|
||||
return result
|
||||
}
|
||||
func qaOpsUsage(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
reader, ok := config.QAOps.(qaUsageReader)
|
||||
if !ok || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
for key, items := range values {
|
||||
if (key != "start" && key != "end" && key != "keyword") || len(items) != 1 {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(config.QAOpsTenantKey, values.Get("start"), values.Get("end"), 90*24*time.Hour, config.Now())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
p, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
query := dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword")}
|
||||
groups, err := reader.ReadUsageGroups(r.Context(), query)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": summarizeQAUsage(groups, p, query)})
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type attributionOrgSpy struct {
|
||||
orgSpy
|
||||
projection *qaopsorg.Attribution
|
||||
}
|
||||
|
||||
func (s *attributionOrgSpy) GetAttribution(context.Context) (*qaopsorg.Attribution, error) {
|
||||
return s.projection, s.err
|
||||
}
|
||||
|
||||
type attributedReader struct{}
|
||||
|
||||
func (*attributedReader) Available(context.Context) error { return nil }
|
||||
func (*attributedReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{SSL: true} }
|
||||
func (*attributedReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: "anonymous"}}, ScopeActors: []dobotaiops.ActorIdentity{{StaffID: "fixture-private-staff"}}, Columns: []string{"question"}, Total: 3}, nil
|
||||
}
|
||||
func (*attributedReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) {
|
||||
return dobotaiops.Record{ID: "one", Department: "历史部门", Region: "历史区域", Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}}, nil
|
||||
}
|
||||
func (*attributedReader) ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
return dobotaiops.UsageGroups{AsOf: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC), Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}, Total: 3, Succeeded: 2, Failed: 1}, {Identity: dobotaiops.ActorIdentity{UnionID: "fixture-private-union"}, Total: 2, Succeeded: 2}, {Identity: dobotaiops.ActorIdentity{StaffID: "unmatched"}, Total: 2}}}, nil
|
||||
}
|
||||
func attributionHandler(t *testing.T) (http.Handler, *attributionOrgSpy) {
|
||||
t.Helper()
|
||||
projection, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "directory-v1", RevisionID: "region-v1", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "APAC"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "测试公司"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
org := &attributionOrgSpy{projection: projection}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["attribution-admin"] = "usr-boss"
|
||||
auth.sessions["attribution-viewer"] = "usr-eye"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: &attributedReader{}, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, org
|
||||
}
|
||||
func attributionRequest(h http.Handler, path, token string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
const attributionFilter = "?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
|
||||
|
||||
func TestQAAttributionUsesWholeFilterAndPreservesHistoricalSnapshots(t *testing.T) {
|
||||
h, org := attributionHandler(t)
|
||||
w := attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
var page struct{ Data dobotaiops.RecordPage }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &page)
|
||||
if !strings.Contains(strings.Join(page.Data.Columns, ","), "department,region") {
|
||||
t.Fatal("organization column hidden because first page is anonymous", w.Body.String())
|
||||
}
|
||||
w = attributionRequest(h, "/api/v1/qa-ops/records/one", "attribution-admin")
|
||||
var detail struct{ Data dobotaiops.Record }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &detail)
|
||||
if detail.Data.Department != "历史部门" || detail.Data.Region != "历史区域" || detail.Data.Organization == nil || detail.Data.Organization.Region != "APAC" {
|
||||
t.Fatal("source snapshot overwritten or current attribution missing", w.Body.String())
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "fixture-private") {
|
||||
t.Fatal("identity keys exposed")
|
||||
}
|
||||
org.err = qaopsorg.ErrUnavailable
|
||||
w = attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin")
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "organization_unavailable") {
|
||||
t.Fatal("permission/storage failure hidden as empty", w.Body.String())
|
||||
}
|
||||
}
|
||||
func TestQAUsageIsAdminScopedDeduplicatedAndNotPerformance(t *testing.T) {
|
||||
h, _ := attributionHandler(t)
|
||||
path := "/api/v1/qa-ops/usage" + attributionFilter
|
||||
for _, tc := range []struct {
|
||||
token string
|
||||
status int
|
||||
}{{"", 401}, {"attribution-viewer", 403}, {"attribution-admin", 200}} {
|
||||
w := attributionRequest(h, path, tc.token)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("usage guard got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if tc.status == 200 {
|
||||
var result struct {
|
||||
Data struct {
|
||||
Questions int64 `json:"questions"`
|
||||
IdentifiedUsers int `json:"identified_users"`
|
||||
Rows []struct {
|
||||
Key string
|
||||
Questions int64
|
||||
Users *int
|
||||
}
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &result) != nil || result.Data.Questions != 7 || result.Data.IdentifiedUsers != 1 {
|
||||
t.Fatal("events/people not deduplicated", w.Body.String())
|
||||
}
|
||||
for _, row := range result.Data.Rows {
|
||||
if row.Key == "APAC" && (row.Questions != 5 || row.Users == nil || *row.Users != 1) {
|
||||
t.Fatal("regional user double-counted")
|
||||
}
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "fixture-private") || strings.Contains(w.Body.String(), "performance") {
|
||||
t.Fatal("private identity or performance verdict leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, extra := range []string{"&tenant=forged", "&limit=1", "&cursor=forged", "&start=duplicate"} {
|
||||
if w := attributionRequest(h, path+extra, "attribution-admin"); w.Code != 400 {
|
||||
t.Fatal("usage accepted client scope or pagination")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,11 +93,17 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
projection, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
enrichQAPage(&page, projection)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
@@ -113,11 +119,17 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
projection, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
item, err := config.QAOps.GetRecord(r.Context(), config.QAOpsTenantKey, r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
enrichQARecord(&item, projection)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": item})
|
||||
}
|
||||
|
||||
@@ -125,6 +137,10 @@ func qaOpsError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusServiceUnavailable
|
||||
code := "source_unavailable"
|
||||
message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响"
|
||||
if errors.Is(err, errQAOrganization) {
|
||||
code = "organization_unavailable"
|
||||
message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试"
|
||||
}
|
||||
if errors.Is(err, dobotaiops.ErrInvalidQuery) {
|
||||
status = http.StatusBadRequest
|
||||
code = "invalid_query"
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type QAOrgStore interface {
|
||||
@@ -33,20 +32,9 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method == http.MethodGet {
|
||||
result, err = config.QAOrg.GetView(r.Context())
|
||||
} else {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
if !authorizeQAOrganizationWrite(w, r) {
|
||||
return
|
||||
}
|
||||
// A same-origin browser request can pass a reverse proxy that rewrites
|
||||
// Host. Fetch Metadata is browser-controlled; keep the explicit action
|
||||
// header and reject cross-site requests without trusting forwarded hosts.
|
||||
if raw := r.Header.Get("Origin"); raw != "" && r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
origin, parseErr := url.Parse(raw)
|
||||
if parseErr != nil || (origin.Scheme != "http" && origin.Scheme != "https") || origin.Host != r.Host {
|
||||
writeJSON(w, 403, map[string]string{"error": "拒绝跨站配置请求"})
|
||||
return
|
||||
}
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type QAOrgSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsorg.SyncStatus, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsorg.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func authorizeQAOrganizationWrite(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
return false
|
||||
}
|
||||
// Fetch Metadata survives same-origin proxies that rewrite Host; untrusted
|
||||
// forwarded headers must not grant cross-origin write authority.
|
||||
if raw := r.Header.Get("Origin"); raw != "" && r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
origin, err := url.Parse(raw)
|
||||
if err != nil || (origin.Scheme != "http" && origin.Scheme != "https") || origin.Host != r.Host {
|
||||
writeJSON(w, 403, map[string]string{"error": "拒绝跨站配置请求"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func qaOrganizationSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method == http.MethodGet {
|
||||
if c.QAOrgSync == nil {
|
||||
writeJSON(w, 200, map[string]any{"data": qaopsorg.SyncStatus{}})
|
||||
return
|
||||
}
|
||||
result, err := c.QAOrgSync.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
result.Configured = c.QAOrgSyncEnabled
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
return
|
||||
}
|
||||
if !authorizeQAOrganizationWrite(w, r) {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&body) != nil || body == nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if !c.QAOrgSyncEnabled || c.QAOrgSync == nil {
|
||||
writeJSON(w, 503, map[string]string{"error": "通讯录后台同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, err := c.QAOrgSync.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if err != nil {
|
||||
if errors.Is(err, qaopsorg.ErrSyncWorkerUnavailable) {
|
||||
writeJSON(w, 503, map[string]string{"error": "通讯录执行器未在线,未创建任务;请检查后台同步配置"})
|
||||
return
|
||||
}
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenericJobCreationCannotBypassDirectorySyncAdminPath(t *testing.T) {
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.directory.sync.fixture","payload":{"triggered_by":"forged"},"idempotency_key":"bypass"}`))
|
||||
res := httptest.NewRecorder()
|
||||
h.ServeHTTP(res, req)
|
||||
if res.Code != 400 {
|
||||
t.Fatalf("reserved sync job bypassed its dedicated admission path: %d", res.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type orgSyncSpy struct {
|
||||
calls int
|
||||
key, actor string
|
||||
replay bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *orgSyncSpy) GetSyncStatus(context.Context) (qaopsorg.SyncStatus, error) {
|
||||
s.calls++
|
||||
return qaopsorg.SyncStatus{Configured: true, WorkerReady: true}, s.err
|
||||
}
|
||||
func (s *orgSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsorg.SyncReceipt, bool, error) {
|
||||
s.calls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsorg.SyncReceipt{JobID: "fixture-job"}, s.replay, s.err
|
||||
}
|
||||
func TestQAOrganizationSyncRequiresAdminIntentAndDurableOperation(t *testing.T) {
|
||||
spy := &orgSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["sync-admin"] = "usr-boss"
|
||||
auth.sessions["sync-viewer"] = "usr-eye"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOrgSync: spy, QAOrgSyncEnabled: true, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "sync-viewer", "", "", "", "", 403}, {"GET", "sync-admin", "", "", "", "", 200},
|
||||
{"POST", "sync-admin", "op-one", "", "", "{}", 403}, {"POST", "sync-admin", "op-one", "qa-organization", "https://evil.invalid", "{}", 403},
|
||||
{"POST", "sync-admin", "", "qa-organization", "", "{}", 400}, {"POST", "sync-admin", " op-one ", "qa-organization", "", "{}", 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", `null`, 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", `{"tenant":"forged"}`, 400}, {"POST", "sync-admin", "op-one", "qa-organization", "", "{} {}", 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/organization/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.action)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != tc.status {
|
||||
t.Fatalf("%+v got %d: %s", tc, res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.calls != 2 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatalf("invalid request reached store: %+v", spy)
|
||||
}
|
||||
spy.replay = true
|
||||
req := httptest.NewRequest("POST", "/api/v1/qa-ops/organization/sync", strings.NewReader("{}"))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "sync-admin"})
|
||||
req.Header.Set("Idempotency-Key", "op-one")
|
||||
req.Header.Set("X-Governance-Action", "qa-organization")
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
var body map[string]any
|
||||
if json.Unmarshal(res.Body.Bytes(), &body) != nil || body["operation"] != "replayed" {
|
||||
t.Fatal("operation replay not exposed")
|
||||
}
|
||||
disabled, _ := NewHandler(Config{Store: &fakeJobStore{}, QAOrgSync: spy, Auth: &AuthConfig{Store: auth}})
|
||||
req.Body = io.NopCloser(strings.NewReader("{}"))
|
||||
res = httptest.NewRecorder()
|
||||
disabled.ServeHTTP(res, req)
|
||||
if res.Code != 503 {
|
||||
t.Fatal("disabled sync enqueued")
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
type JobStore interface {
|
||||
@@ -101,6 +102,8 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
QAOps QAOpsReader
|
||||
QAOpsTenantKey string
|
||||
@@ -172,6 +175,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/usage", func(w http.ResponseWriter, r *http.Request) { qaOpsUsage(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/preview", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("PUT /api/v1/qa-ops/organization/regions", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
@@ -556,6 +562,10 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON request"})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Type) == "" || len(input.Type) > 100 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type is required and must not exceed 100 characters"})
|
||||
return
|
||||
|
||||
@@ -20,6 +20,12 @@ var ErrOperationRequestConflict = errors.New("operation request conflicts with a
|
||||
|
||||
type operationExecutor func(pgx.Tx) (json.RawMessage, error)
|
||||
|
||||
// ExecuteOperation lets bounded modules share the durable operation transaction
|
||||
// instead of caching responses after their business writes have committed.
|
||||
func (s *Store) ExecuteOperation(ctx context.Context, operationType, operationID, fingerprint string, now time.Time, execute func(pgx.Tx) (json.RawMessage, error)) (json.RawMessage, bool, error) {
|
||||
return s.executeOperation(ctx, operationType, operationID, fingerprint, now, execute)
|
||||
}
|
||||
|
||||
func (s *Store) RouteCatalogFilesWithOperation(ctx context.Context, request governance.CatalogRouteRequest, operationID string) (governance.CatalogRouteResult, bool, error) {
|
||||
if err := validateCatalogRouteRequest(request); err != nil {
|
||||
return governance.CatalogRouteResult{}, false, err
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type PersonAttribution struct {
|
||||
State string `json:"state"`
|
||||
PersonID string `json:"-"`
|
||||
Departments []string `json:"departments"`
|
||||
Region string `json:"region"`
|
||||
}
|
||||
type Attribution struct {
|
||||
Metadata State
|
||||
people map[string]PersonAttribution
|
||||
unions map[string]string
|
||||
}
|
||||
|
||||
func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
p := &Attribution{Metadata: state, people: map[string]PersonAttribution{}, unions: map[string]string{}}
|
||||
if state.State == "empty" {
|
||||
return p, nil
|
||||
}
|
||||
if state.State != "ready" || state.DirectoryID == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
view, err := Preview(directory, state.Rules)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
p.Metadata.View = view
|
||||
departments := map[string]DepartmentView{}
|
||||
for _, d := range view.Departments {
|
||||
departments[d.ID] = d
|
||||
}
|
||||
for _, person := range directory.People {
|
||||
paths, regions := map[string]bool{}, map[string]bool{}
|
||||
for _, id := range person.DepartmentIDs {
|
||||
d := departments[id]
|
||||
paths[d.Path] = true
|
||||
if d.Region != "" {
|
||||
regions[d.Region] = true
|
||||
}
|
||||
}
|
||||
item := PersonAttribution{State: "unassigned", PersonID: person.ID, Departments: []string{}}
|
||||
for path := range paths {
|
||||
item.Departments = append(item.Departments, path)
|
||||
}
|
||||
sort.Strings(item.Departments)
|
||||
if len(regions) == 1 {
|
||||
item.State = "matched"
|
||||
for region := range regions {
|
||||
item.Region = region
|
||||
}
|
||||
} else if len(regions) > 1 {
|
||||
item.State = "cross_region"
|
||||
}
|
||||
p.people[person.ID] = item
|
||||
if person.UnionID != "" {
|
||||
if !validID(person.UnionID) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if _, ok := p.unions[person.UnionID]; ok {
|
||||
p.unions[person.UnionID] = ""
|
||||
} else {
|
||||
p.unions[person.UnionID] = person.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
func (p *Attribution) Resolve(staff, union string) PersonAttribution {
|
||||
none := PersonAttribution{State: "unmatched", Departments: []string{}}
|
||||
if p == nil || p.Metadata.State != "ready" {
|
||||
none.State = "directory_missing"
|
||||
return none
|
||||
}
|
||||
if staff == "" && union == "" {
|
||||
none.State = "no_identity"
|
||||
return none
|
||||
}
|
||||
byUnion, unionKnown := p.unions[union]
|
||||
if person, ok := p.people[staff]; ok {
|
||||
if unionKnown && (byUnion == "" || byUnion != staff) {
|
||||
none.State = "identity_conflict"
|
||||
return none
|
||||
}
|
||||
return person
|
||||
}
|
||||
if unionKnown {
|
||||
if byUnion == "" {
|
||||
none.State = "identity_conflict"
|
||||
return none
|
||||
}
|
||||
return p.people[byUnion]
|
||||
}
|
||||
return none
|
||||
}
|
||||
func (s *Store) GetAttribution(ctx context.Context) (*Attribution, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
state, directory, err := s.read(ctx, s.pool, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return BuildAttribution(state, directory)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAttributionUsesStableIdentityAndKeepsAmbiguitiesExplicit(t *testing.T) {
|
||||
d := Directory{Departments: []Department{{ID: "root", Name: "fixture"}, {ID: "a", ParentID: "root", Name: "one"}, {ID: "b", ParentID: "root", Name: "two"}}, People: []Person{{ID: "staff-a", UnionID: "union-a", DepartmentIDs: []string{"a", "a"}}, {ID: "staff-cross", UnionID: "union-cross", DepartmentIDs: []string{"a", "b"}}, {ID: "duplicate-one", UnionID: "duplicate", DepartmentIDs: []string{"a"}}, {ID: "duplicate-two", UnionID: "duplicate", DepartmentIDs: []string{"b"}}}}
|
||||
p, err := BuildAttribution(State{State: "ready", DirectoryID: "d", RevisionID: "r", Rules: []Rule{{DepartmentID: "root", Region: "国内工业"}, {DepartmentID: "b", Region: "APAC"}}}, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range [][2]string{{"staff-a", ""}, {"", "union-a"}} {
|
||||
got := p.Resolve(key[0], key[1])
|
||||
if got.State != "matched" || got.Region != "国内工业" || len(got.Departments) != 1 || got.PersonID != "staff-a" {
|
||||
t.Fatalf("stable identity not resolved/deduplicated: %+v", got)
|
||||
}
|
||||
}
|
||||
if got := p.Resolve("staff-cross", ""); got.State != "cross_region" || got.Region != "" || len(got.Departments) != 2 {
|
||||
t.Fatalf("invented primary region: %+v", got)
|
||||
}
|
||||
if got := p.Resolve("", "duplicate"); got.State != "identity_conflict" {
|
||||
t.Fatalf("duplicate union selected first person: %+v", got)
|
||||
}
|
||||
if got := p.Resolve("staff-a", "union-cross"); got.State != "identity_conflict" {
|
||||
t.Fatalf("contradictory identifiers silently preferred: %+v", got)
|
||||
}
|
||||
if got := p.Resolve("absent", ""); got.State != "unmatched" {
|
||||
t.Fatalf("unknown identity inferred: %+v", got)
|
||||
}
|
||||
if got := p.Resolve("", ""); got.State != "no_identity" {
|
||||
t.Fatalf("anonymous identity inferred: %+v", got)
|
||||
}
|
||||
}
|
||||
func TestAttributionDoesNotTreatMissingDirectoryAsPermissionSuccess(t *testing.T) {
|
||||
p, err := BuildAttribution(State{State: "empty"}, Directory{})
|
||||
if err != nil || p.Resolve("staff", "").State != "directory_missing" {
|
||||
t.Fatal("missing directory not explicit")
|
||||
}
|
||||
var store *Store
|
||||
if _, err = store.GetAttribution(context.Background()); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal("unavailable store returned an empty directory")
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
@@ -176,6 +177,9 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
return next, nil
|
||||
}
|
||||
func (s *Store) ReplaceDirectory(ctx context.Context, input Import) (State, error) {
|
||||
return s.replaceDirectory(ctx, input, nil)
|
||||
}
|
||||
func (s *Store) replaceDirectory(ctx context.Context, input Import, lease *jobs.Job) (State, error) {
|
||||
if !s.available() {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -197,6 +201,11 @@ func (s *Store) ReplaceDirectory(ctx context.Context, input Import) (State, erro
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
if lease != nil {
|
||||
if _, err = s.syncLease(ctx, tx, *lease, true); err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_directory_snapshots(tenant_key,id,source,synced_at,payload) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_key,id) DO NOTHING`, s.tenant, id, input.Source, input.SyncedAt, payload); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -207,6 +216,16 @@ func (s *Store) ReplaceDirectory(ctx context.Context, input Import) (State, erro
|
||||
if tag.RowsAffected() != 1 {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
if lease != nil {
|
||||
result, _ := json.Marshal(SyncResult{DirectoryID: id, Departments: len(input.Directory.Departments), People: len(input.Directory.People), SyncedAt: input.SyncedAt})
|
||||
tag, err = tx.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{result}',$3::jsonb),updated_at=now() WHERE id=$1 AND lease_owner=$2 AND state='running' AND lease_until>clock_timestamp() AND attempt=$4`, lease.ID, lease.LeaseOwner, result, lease.Attempt)
|
||||
if err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return State{}, ErrSyncLease
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -62,6 +62,10 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err != nil || read.RevisionID != saved.RevisionID || read.View.Regions["国内工业"] != 1 {
|
||||
t.Fatal("saved rules not consumed by read path")
|
||||
}
|
||||
projection, projectionErr := store.GetAttribution(ctx)
|
||||
if projectionErr != nil || projection.Metadata.DirectoryID != read.DirectoryID || projection.Metadata.RevisionID != read.RevisionID || projection.Resolve("u2", "").Region != "APAC" {
|
||||
t.Fatal("attribution did not consume the saved directory/region revision")
|
||||
}
|
||||
if _, err = store.SaveRules(ctx, request, "stale-admin"); !errors.Is(err, qaopsorg.ErrConflict) {
|
||||
t.Fatalf("stale update overwrote newer rules: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
var ErrSyncWorkerUnavailable = errors.New("directory sync worker is not connected")
|
||||
|
||||
const SyncJobPrefix = "qaops.directory.sync."
|
||||
|
||||
var ErrSyncLease = errors.New("directory sync lease is no longer owned")
|
||||
|
||||
type DirectoryRunner interface {
|
||||
Run(context.Context) (Import, error)
|
||||
}
|
||||
type SyncReceipt struct {
|
||||
JobID string `json:"job_id"`
|
||||
Deduplicated bool `json:"deduplicated"`
|
||||
}
|
||||
type SyncResult struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
Departments int `json:"departments"`
|
||||
People int `json:"people"`
|
||||
SyncedAt time.Time `json:"synced_at"`
|
||||
}
|
||||
type SyncJob struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Attempt int `json:"attempt"`
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
type SyncStatus struct {
|
||||
Configured bool `json:"configured"`
|
||||
WorkerReady bool `json:"worker_ready"`
|
||||
Job *SyncJob `json:"job"`
|
||||
}
|
||||
|
||||
func (s *Store) SyncJobType() string {
|
||||
h := sha256.Sum256([]byte(s.tenant))
|
||||
return SyncJobPrefix + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
const syncWorkerReadySQL = `SELECT EXISTS(SELECT 1 FROM worker_heartbeats WHERE $1=ANY(string_to_array(job_types,',')) AND last_seen_at>clock_timestamp()-interval '2 minutes') OR EXISTS(SELECT 1 FROM jobs WHERE type=$1 AND state='running' AND lease_until>clock_timestamp())`
|
||||
|
||||
func (s *Store) EnqueueSync(ctx context.Context, key, actor string) (SyncReceipt, bool, error) {
|
||||
if !s.available() {
|
||||
return SyncReceipt{}, false, ErrUnavailable
|
||||
}
|
||||
if !validID(key) || len(key) > 128 || !validID(actor) {
|
||||
return SyncReceipt{}, false, ErrInvalid
|
||||
}
|
||||
fp := sha256.Sum256([]byte(actor))
|
||||
now := time.Now()
|
||||
raw, replayed, err := postgresstore.NewStore(s.pool).ExecuteOperation(ctx, s.SyncJobType(), key, hex.EncodeToString(fp[:]), now, func(tx pgx.Tx) (json.RawMessage, error) {
|
||||
if _, e := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", s.SyncJobType()); e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
// A last-attempt process may die without recording failure. A new explicit
|
||||
// action retires that exhausted lease; it never impersonates a live owner.
|
||||
if _, e := tx.Exec(ctx, `UPDATE jobs SET state='failed',last_error='directory worker stopped; previous snapshot retained',last_error_code='directory_sync_failed',lease_owner=NULL,lease_until=NULL,updated_at=now() WHERE type=$1 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, s.SyncJobType()); e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var active string
|
||||
e := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&active)
|
||||
if e == nil {
|
||||
return json.Marshal(SyncReceipt{JobID: active, Deduplicated: true})
|
||||
}
|
||||
if !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var ready bool
|
||||
if tx.QueryRow(ctx, syncWorkerReadySQL, s.SyncJobType()).Scan(&ready) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if !ready {
|
||||
return nil, ErrSyncWorkerUnavailable
|
||||
}
|
||||
digest := sha256.Sum256([]byte(s.SyncJobType() + ":" + key))
|
||||
id := "job-" + hex.EncodeToString(digest[:16])
|
||||
payload, _ := json.Marshal(map[string]string{"triggered_by": actor})
|
||||
job, e := postgresstore.NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: s.SyncJobType(), Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: s.SyncJobType() + ":" + key}, now)
|
||||
if e != nil || job == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return json.Marshal(SyncReceipt{JobID: job.ID})
|
||||
})
|
||||
if errors.Is(err, postgresstore.ErrOperationRequestConflict) {
|
||||
return SyncReceipt{}, false, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return SyncReceipt{}, false, err
|
||||
}
|
||||
var result SyncReceipt
|
||||
if json.Unmarshal(raw, &result) != nil || result.JobID == "" {
|
||||
return SyncReceipt{}, false, ErrUnavailable
|
||||
}
|
||||
return result, replayed, nil
|
||||
}
|
||||
func (s *Store) GetSyncStatus(ctx context.Context) (SyncStatus, error) {
|
||||
result := SyncStatus{Configured: true}
|
||||
if !s.available() {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
if s.pool.QueryRow(ctx, syncWorkerReadySQL, s.SyncJobType()).Scan(&result.WorkerReady) != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
var job SyncJob
|
||||
var payload []byte
|
||||
var expired bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,state,attempt,max_attempts,updated_at,payload,COALESCE(state='running' AND lease_until<clock_timestamp(),false) FROM jobs WHERE type=$1 ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&job.ID, &job.State, &job.Attempt, &job.MaxAttempts, &job.UpdatedAt, &payload, &expired)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return result, nil
|
||||
}
|
||||
if err != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
var parsed struct {
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(payload, &parsed) != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
job.Result = parsed.Result
|
||||
if expired {
|
||||
job.State = "retry"
|
||||
if job.Attempt >= job.MaxAttempts {
|
||||
job.State = "failed"
|
||||
}
|
||||
}
|
||||
if job.State == "failed" || job.State == "retry" {
|
||||
job.ErrorCode = "directory_sync_failed"
|
||||
}
|
||||
result.Job = &job
|
||||
return result, nil
|
||||
}
|
||||
func (s *Store) syncLease(ctx context.Context, q orgQuerier, job jobs.Job, lock bool) (*SyncResult, error) {
|
||||
if job.Type != s.SyncJobType() || job.LeaseOwner == "" {
|
||||
return nil, ErrSyncLease
|
||||
}
|
||||
query := `SELECT payload FROM jobs WHERE id=$1 AND type=$2 AND state='running' AND lease_owner=$3 AND attempt=$4 AND lease_until>clock_timestamp() AND EXISTS(SELECT 1 FROM operation_requests op WHERE op.operation_type=jobs.type AND op.result->>'job_id'=jobs.id)`
|
||||
if lock {
|
||||
query += " FOR UPDATE"
|
||||
}
|
||||
var raw []byte
|
||||
if q.QueryRow(ctx, query, job.ID, s.SyncJobType(), job.LeaseOwner, job.Attempt).Scan(&raw) != nil {
|
||||
return nil, ErrSyncLease
|
||||
}
|
||||
var payload struct {
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return payload.Result, nil
|
||||
}
|
||||
func (s *Store) HandleDirectorySync(ctx context.Context, job jobs.Job, runner DirectoryRunner) error {
|
||||
if !s.available() || runner == nil {
|
||||
return ErrDirectorySync
|
||||
}
|
||||
result, err := s.syncLease(ctx, s.pool, job, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result != nil {
|
||||
return nil
|
||||
}
|
||||
input, err := runner.Run(ctx)
|
||||
if err != nil {
|
||||
return ErrDirectorySync
|
||||
}
|
||||
if input.Source != "weekly_report_live" {
|
||||
return jobs.Permanent("directory_sync_failed", ErrDirectorySync)
|
||||
}
|
||||
_, err = s.replaceDirectory(ctx, input, &job)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrSyncLease) {
|
||||
return err
|
||||
}
|
||||
return ErrDirectorySync
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package qaopsorg_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
type syncRunner func(context.Context) (qaopsorg.Import, error)
|
||||
|
||||
func (f syncRunner) Run(ctx context.Context) (qaopsorg.Import, error) { return f(ctx) }
|
||||
func TestDirectorySyncQueueDurableReplayAndLeaseFencing(t *testing.T) {
|
||||
dsn := os.Getenv("KG_QAOPS_ORG_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit isolated organization database is not configured")
|
||||
}
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_org_test_") || os.Getenv("KG_QAOPS_ORG_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing non-isolated organization database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal("isolated connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, "sync-fixture-tenant")
|
||||
queue := postgresstore.NewStore(pool)
|
||||
initial := qaopsorg.Import{Source: "weekly_report_live", Complete: true, SyncedAt: time.Now().Add(-time.Hour), Directory: qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "同步夹具"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"root"}}}}}
|
||||
old, err := store.ReplaceDirectory(ctx, initial)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := store.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: old.DirectoryID, Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "APAC"}}}, "fixture-admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = store.EnqueueSync(ctx, "op-no-worker", "fixture-admin"); !errors.Is(err, qaopsorg.ErrSyncWorkerUnavailable) {
|
||||
t.Fatalf("disconnected worker accepted: %v", err)
|
||||
}
|
||||
if _, err = queue.Claim(ctx, "fixture-sync-worker", []string{store.SyncJobType()}, time.Now(), time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first qaopsorg.SyncReceipt
|
||||
var created atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
failures := make(chan error, 12)
|
||||
ids := make(chan string, 12)
|
||||
for range 12 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r, replay, e := qaopsorg.NewStore(pool, "sync-fixture-tenant").EnqueueSync(ctx, "op-same-action", "fixture-admin")
|
||||
if e != nil {
|
||||
failures <- e
|
||||
return
|
||||
}
|
||||
if !replay {
|
||||
created.Add(1)
|
||||
}
|
||||
ids <- r.JobID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
for e := range failures {
|
||||
t.Fatal(e)
|
||||
}
|
||||
close(ids)
|
||||
for id := range ids {
|
||||
if first.JobID == "" {
|
||||
first.JobID = id
|
||||
}
|
||||
if id != first.JobID {
|
||||
t.Fatal("duplicate effect")
|
||||
}
|
||||
}
|
||||
if created.Load() != 1 {
|
||||
t.Fatal("operation replay was not durable")
|
||||
}
|
||||
reused, _, err := store.EnqueueSync(ctx, "op-another-click", "fixture-admin")
|
||||
if err != nil || !reused.Deduplicated || reused.JobID != first.JobID {
|
||||
t.Fatal("in-flight clicks did not coalesce")
|
||||
}
|
||||
if _, _, err = store.EnqueueSync(ctx, "op-same-action", "another-admin"); !errors.Is(err, qaopsorg.ErrConflict) {
|
||||
t.Fatal("actor fingerprint conflict ignored")
|
||||
}
|
||||
other, _ := qaopsorg.NewStore(pool, "other-sync-tenant").GetSyncStatus(ctx)
|
||||
if other.Job != nil {
|
||||
t.Fatal("job leaked across tenants")
|
||||
}
|
||||
var n int
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM jobs WHERE type=$1", store.SyncJobType()).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("job count must remain one")
|
||||
}
|
||||
job, err := queue.Claim(ctx, "worker-before-crash", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || job == nil {
|
||||
t.Fatal("job was not durable/claimable")
|
||||
}
|
||||
// A different process can reclaim expired work; the old owner must not activate data.
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET lease_until=now()-interval '1 second' WHERE id=$1", job.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reclaimed, err := queue.Claim(ctx, "worker-after-restart", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || reclaimed == nil || reclaimed.Attempt != 2 {
|
||||
t.Fatal("expired lease did not resume")
|
||||
}
|
||||
newer := initial
|
||||
newer.SyncedAt = time.Now()
|
||||
newer.Directory.People = append(append([]qaopsorg.Person{}, initial.Directory.People...), qaopsorg.Person{ID: "fixture-person-2", DepartmentIDs: []string{"root"}})
|
||||
var fetched atomic.Int32
|
||||
run := syncRunner(func(context.Context) (qaopsorg.Import, error) { fetched.Add(1); return newer, nil })
|
||||
if err = store.HandleDirectorySync(ctx, *job, run); err == nil {
|
||||
t.Fatal("stale owner activated a snapshot")
|
||||
}
|
||||
still, _ := store.GetView(ctx)
|
||||
if still.DirectoryID != old.DirectoryID {
|
||||
t.Fatal("stale lease changed active data")
|
||||
}
|
||||
if err = store.HandleDirectorySync(ctx, *reclaimed, run); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := fetched.Load()
|
||||
// Crash after committing the snapshot, before queue.Complete: do not fetch twice.
|
||||
if err = store.HandleDirectorySync(ctx, *reclaimed, run); err != nil || fetched.Load() != count {
|
||||
t.Fatal("committed source was fetched again")
|
||||
}
|
||||
if err = queue.Complete(ctx, reclaimed.ID, reclaimed.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, _ := store.GetView(ctx)
|
||||
if current.View.TotalPeople != 2 || current.RevisionID != saved.RevisionID || current.View.Regions["APAC"] != 2 {
|
||||
t.Fatal("refresh lost regional rules or failed to activate")
|
||||
}
|
||||
status, err := store.GetSyncStatus(ctx)
|
||||
if err != nil || status.Job == nil || status.Job.State != "completed" || status.Job.Result == nil || status.Job.Result.People != 2 {
|
||||
t.Fatal("safe status missing durable result")
|
||||
}
|
||||
raw, _ := json.Marshal(status)
|
||||
if strings.Contains(string(raw), "fixture-person") || strings.Contains(string(raw), "lease_owner") {
|
||||
t.Fatal("personnel/lease details leaked in status")
|
||||
}
|
||||
// Failure must preserve the previous complete directory and never store raw exceptions.
|
||||
failed, _, err := store.EnqueueSync(ctx, "op-fails", "fixture-admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad, err := queue.Claim(ctx, "worker-failure", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || bad == nil || bad.ID != failed.JobID {
|
||||
t.Fatal("failure job was not enqueued")
|
||||
}
|
||||
failure := store.HandleDirectorySync(ctx, *bad, syncRunner(func(context.Context) (qaopsorg.Import, error) {
|
||||
return qaopsorg.Import{}, errors.New("sensitive-fixture-must-not-escape")
|
||||
}))
|
||||
if failure == nil || strings.Contains(failure.Error(), "sensitive-fixture") {
|
||||
t.Fatal("unsafe source exception")
|
||||
}
|
||||
if err = queue.Fail(ctx, bad.ID, bad.LeaseOwner, failure.Error(), "directory_sync_failed", time.Now(), time.Now().Add(time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, _ := store.GetView(ctx)
|
||||
if kept.DirectoryID != current.DirectoryID || kept.RevisionID != saved.RevisionID {
|
||||
t.Fatal("failed refresh replaced valid state")
|
||||
}
|
||||
late := qaopsorg.NewStore(pool, "late-fence-tenant")
|
||||
lateOld, err := late.ReplaceDirectory(ctx, initial)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = queue.Claim(ctx, "late-worker", []string{late.SyncJobType()}, time.Now(), time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = late.EnqueueSync(ctx, "op-late-fence", "fixture-admin"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lateJob, err := queue.Claim(ctx, "late-worker", []string{late.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || lateJob == nil {
|
||||
t.Fatal("late-fence job unavailable")
|
||||
}
|
||||
lateErr := late.HandleDirectorySync(ctx, *lateJob, syncRunner(func(context.Context) (qaopsorg.Import, error) {
|
||||
_, failure := pool.Exec(ctx, "UPDATE jobs SET lease_owner='replacement-worker',attempt=attempt+1,lease_until=now()+interval '1 minute' WHERE id=$1", lateJob.ID)
|
||||
return newer, failure
|
||||
}))
|
||||
if lateErr == nil {
|
||||
t.Fatal("lease lost DURING source fetch was not fenced at commit")
|
||||
}
|
||||
lateKept, _ := late.GetView(ctx)
|
||||
if lateKept.DirectoryID != lateOld.DirectoryID {
|
||||
t.Fatal("late stale worker activated data")
|
||||
}
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_directory_snapshots WHERE tenant_key=$1", "late-fence-tenant").Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("rejected stale snapshot left durable rows")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET lease_until=now()-interval '1 second' WHERE id=$1", lateJob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
interrupted, err := late.GetSyncStatus(ctx)
|
||||
if err != nil || interrupted.Job == nil || interrupted.Job.State != "retry" {
|
||||
t.Fatal("interrupted lease must wait for takeover, not claim active source processing")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET attempt=max_attempts,lease_until=now()-interval '1 second' WHERE id=$1", lateJob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exhausted, err := late.GetSyncStatus(ctx)
|
||||
if err != nil || exhausted.Job == nil || exhausted.Job.State != "failed" {
|
||||
t.Fatal("exhausted crashed worker reported running forever")
|
||||
}
|
||||
fresh, _, err := late.EnqueueSync(ctx, "op-after-exhausted", "fixture-admin")
|
||||
if err != nil || fresh.JobID == lateJob.ID {
|
||||
t.Fatal("explicit retry could not replace an exhausted crashed job")
|
||||
}
|
||||
ghost := qaopsorg.NewStore(pool, "unadmitted-tenant")
|
||||
if _, err = ghost.ReplaceDirectory(ctx, initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = queue.Enqueue(ctx, jobs.EnqueueRequest{ID: "fixture-unadmitted-job", Type: ghost.SyncJobType(), Payload: json.RawMessage(`{}`), AvailableAt: time.Now(), MaxAttempts: 1, IdempotencyKey: "fixture-unadmitted-job"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ghostJob, err := queue.Claim(ctx, "ghost-worker", []string{ghost.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || ghostJob == nil {
|
||||
t.Fatal("forged fixture unavailable")
|
||||
}
|
||||
var ghostCalls int
|
||||
ghostErr := ghost.HandleDirectorySync(ctx, *ghostJob, syncRunner(func(context.Context) (qaopsorg.Import, error) { ghostCalls++; return newer, nil }))
|
||||
if ghostErr == nil || ghostCalls != 0 {
|
||||
t.Fatal("unadmitted generic task consumed the directory source")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SyncSettings struct {
|
||||
Enabled bool
|
||||
Tenant string
|
||||
Runner ExecDirectoryRunner
|
||||
}
|
||||
|
||||
func LoadSyncSettings(getenv func(string) string) (SyncSettings, error) {
|
||||
var s SyncSettings
|
||||
enabled := getenv("DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED")
|
||||
if enabled == "" || enabled == "false" {
|
||||
return s, nil
|
||||
}
|
||||
if enabled != "true" {
|
||||
return s, errors.New("invalid directory sync enable flag")
|
||||
}
|
||||
s.Tenant = getenv("DOBOTAI_OPS_TENANT_KEY")
|
||||
s.Runner = ExecDirectoryRunner{Python: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"), Script: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"), RuntimeRoot: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"), SpoolRoot: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"), Timeout: 20 * time.Minute}
|
||||
if value := getenv("DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"); value != "" {
|
||||
d, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return SyncSettings{}, errors.New("invalid directory sync timeout")
|
||||
}
|
||||
s.Runner.Timeout = d
|
||||
}
|
||||
if !validID(s.Tenant) || s.Runner.Timeout < time.Second || s.Runner.Timeout > 30*time.Minute {
|
||||
return SyncSettings{}, errors.New("directory sync binding is incomplete")
|
||||
}
|
||||
for _, path := range []string{s.Runner.Python, s.Runner.Script, s.Runner.RuntimeRoot, s.Runner.SpoolRoot} {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
||||
return SyncSettings{}, errors.New("directory sync requires server-owned absolute paths")
|
||||
}
|
||||
}
|
||||
s.Enabled = true
|
||||
return s, nil
|
||||
}
|
||||
func (s SyncSettings) CheckWorkerRuntime() error {
|
||||
for _, path := range []string{s.Runner.Python, s.Runner.Script} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return ErrSyncWorkerUnavailable
|
||||
}
|
||||
}
|
||||
for _, path := range []string{s.Runner.RuntimeRoot, s.Runner.SpoolRoot} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || !info.IsDir() {
|
||||
return ErrSyncWorkerUnavailable
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDirectorySyncSettingsAreExplicitAndServerOwned(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
off, err := LoadSyncSettings(get)
|
||||
if err != nil || off.Enabled {
|
||||
t.Fatal("sync must default off")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED"] = "true"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("unbound runtime accepted")
|
||||
}
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-tenant"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"] = "/usr/bin/python3"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = "/app/scripts/qa_ops_directory_sync.py"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"] = "/data/weekly-report"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"] = "/data/private-spool"
|
||||
ready, err := LoadSyncSettings(get)
|
||||
if err != nil || !ready.Enabled || ready.Runner.Timeout != 20*time.Minute {
|
||||
t.Fatal("valid runtime not configured")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"] = "31m"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("unbounded source timeout")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"] = "10m"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = "relative/script.py"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("browser-like relative script accepted")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,13 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"optional": [
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQARecordInternalIdentityAndWholeFilterKeys", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsorg",
|
||||
"test": "TestDirectorySyncQueueDurableReplayAndLeaseFencing",
|
||||
"reason": "仅显式一次性隔离PG库验证持久化入队、并发重放、进程接管与租约栅栏;不调用真实钉钉源、不连接共享或生产库;默认CI无库则明确跳过"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsorg",
|
||||
"test": "TestOrganizationStoreRoundTripAndOptimisticConflict",
|
||||
|
||||
+79
-30
@@ -1,10 +1,12 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { fetchQARecord, fetchQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
|
||||
import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps'
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { QARegions } from './QARegions'
|
||||
import { QAUsage } from './QAUsage'
|
||||
import { usageLabels } from './qaUsage'
|
||||
|
||||
interface ViewProps {
|
||||
page: QARecordPage | null
|
||||
@@ -48,6 +50,13 @@ export function QAOperationsView(props: ViewProps) {
|
||||
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{page?.organization ? (
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
{page.organization.state === 'ready'
|
||||
? `缺失组织信息按当前通讯录补全(${stamp(page.organization.synced_at!)}),不代表提问时归属。目录:${page.organization.directory_id};区域版本:${page.organization.revision_id || '未保存'}`
|
||||
: '尚无完整通讯录,仅展示源端已有组织快照,不根据姓名推断。'}
|
||||
</p>
|
||||
) : null}
|
||||
{props.status?.warnings.map((warning) => (
|
||||
<p className="qa-ops-warning" key={warning}>
|
||||
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
|
||||
@@ -79,7 +88,9 @@ export function QAOperationsView(props: ViewProps) {
|
||||
<td
|
||||
key={key}
|
||||
className={
|
||||
key === 'answer' || key === 'question' || key === 'question_chinese' ? 'qa-ops-text-cell' : ''
|
||||
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
|
||||
? 'qa-ops-text-cell'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<span
|
||||
@@ -174,6 +185,40 @@ export function QAOperationsView(props: ViewProps) {
|
||||
</dd>
|
||||
<dt>提问人</dt>
|
||||
<dd>{detail.asker || '未关联'}</dd>
|
||||
<dt>部门</dt>
|
||||
<dd>
|
||||
{detail.department || '未匹配'}
|
||||
{detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''}
|
||||
</dd>
|
||||
<dt>区域</dt>
|
||||
<dd>
|
||||
{detail.region || '未配置/待核对'}
|
||||
{detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''}
|
||||
</dd>
|
||||
{detail.organization ? (
|
||||
<>
|
||||
<dt>当前组织关联</dt>
|
||||
<dd>
|
||||
{detail.organization.state === 'matched'
|
||||
? '已关联'
|
||||
: (usageLabels[detail.organization.state] ?? detail.organization.state)}
|
||||
</dd>
|
||||
<dt>当前通讯录部门/区域</dt>
|
||||
<dd>
|
||||
{detail.organization.departments.join(';') || '未匹配'} /{' '}
|
||||
{detail.organization.region || '未配置或待核对'}
|
||||
</dd>
|
||||
<dt>组织版本</dt>
|
||||
<dd>
|
||||
{detail.organization.version.directory_id || '无完整目录'} /{' '}
|
||||
{detail.organization.version.revision_id || '未保存区域配置'}
|
||||
</dd>
|
||||
<dt>源端组织快照</dt>
|
||||
<dd>
|
||||
{detail.organization.source_department || '空'} / {detail.organization.source_region || '空'}
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
<dt>问答状态</dt>
|
||||
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
|
||||
<dt>流程触发人员信息</dt>
|
||||
@@ -230,7 +275,7 @@ function initialDraft() {
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
const [view, setView] = useState<'records' | 'regions'>('records')
|
||||
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
|
||||
const auth = useOptionalAuth()
|
||||
const canRead = auth?.identity?.role === 'admin'
|
||||
const [draft, setDraft] = useState(initialDraft)
|
||||
@@ -260,6 +305,13 @@ export function QAOperations() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!query || !canRead) return
|
||||
if (view !== 'records') {
|
||||
setLoading(false)
|
||||
moreRequest.current?.abort()
|
||||
detailRequest.current?.abort()
|
||||
setDetail(null)
|
||||
return
|
||||
}
|
||||
const controller = new AbortController()
|
||||
generation.current += 1
|
||||
moreRequest.current?.abort()
|
||||
@@ -286,7 +338,7 @@ export function QAOperations() {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [query, canRead, revision])
|
||||
}, [query, canRead, revision, view])
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -341,17 +393,7 @@ export function QAOperations() {
|
||||
try {
|
||||
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
|
||||
if (!controller.signal.aborted && currentGeneration === generation.current) {
|
||||
setPage((current) =>
|
||||
current
|
||||
? {
|
||||
...result,
|
||||
items: [
|
||||
...current.items,
|
||||
...result.items.filter((item) => !current.items.some(({ id }) => id === item.id)),
|
||||
],
|
||||
}
|
||||
: result
|
||||
)
|
||||
setPage(mergeQAPages(page, result))
|
||||
}
|
||||
} catch (reason) {
|
||||
if (!controller.signal.aborted && currentGeneration === generation.current)
|
||||
@@ -364,7 +406,7 @@ export function QAOperations() {
|
||||
<section className="qa-ops" aria-label="问答运营">
|
||||
<header className="qa-ops-header">
|
||||
<h2>
|
||||
问答运营 <span>/ {view === 'regions' ? '区域归属' : '问答记录'}</span>
|
||||
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
|
||||
</h2>
|
||||
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
|
||||
</header>
|
||||
@@ -378,6 +420,9 @@ export function QAOperations() {
|
||||
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
|
||||
问答记录
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
|
||||
使用统计
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
|
||||
区域使用
|
||||
</button>
|
||||
@@ -420,21 +465,25 @@ export function QAOperations() {
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-slice-note">
|
||||
当前切片:问答查询与覆盖复检。外语翻译、AI评估及人员映射尚未接入;空值不默认填“否”。
|
||||
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
|
||||
</p>
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
onLoadMore={() => void loadMore()}
|
||||
onRetry={() => setRevision((value) => value + 1)}
|
||||
/>
|
||||
{view === 'usage' ? (
|
||||
<QAUsage query={query} />
|
||||
) : (
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
onLoadMore={() => void loadMore()}
|
||||
onRetry={() => setRevision((value) => value + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -51,6 +51,30 @@ const props = {
|
||||
onRemoveMissing: vi.fn(),
|
||||
}
|
||||
describe('region mapping workbench', () => {
|
||||
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
|
||||
const syncStatus = {
|
||||
configured: true,
|
||||
worker_ready: true,
|
||||
job: {
|
||||
id: 'j',
|
||||
state: 'running' as const,
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T08:00:00Z',
|
||||
error_code: '',
|
||||
result: null,
|
||||
},
|
||||
}
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} syncStatus={syncStatus} />)
|
||||
expect(html).toContain('正在读取并校验通讯录')
|
||||
expect(html).not.toMatch(/\d+%/)
|
||||
expect(html).toMatch(/disabled=""[^>]*>同步通讯录/)
|
||||
const dirty = renderToStaticMarkup(
|
||||
<RegionMappingView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
|
||||
)
|
||||
expect(dirty).toContain('未保存的区域修改')
|
||||
expect(dirty).toMatch(/disabled=""[^>]*>同步通讯录/)
|
||||
})
|
||||
it('lets long directory paths wrap instead of inheriting the global nowrap table rule', () => {
|
||||
const css = readFileSync(new URL('./qaRegions.css', import.meta.url), 'utf8')
|
||||
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
|
||||
+128
-2
@@ -2,7 +2,14 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
|
||||
import type { Organization, RegionRule } from './qaOrg'
|
||||
import './qaRegions.css'
|
||||
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
|
||||
import type { DirectorySyncStatus } from './qaOrgSync'
|
||||
import { newOperationID } from './operationKey'
|
||||
interface Props {
|
||||
syncStatus?: DirectorySyncStatus | null
|
||||
syncError?: string
|
||||
syncSubmitting?: boolean
|
||||
onSync?: () => void
|
||||
state: Organization | null
|
||||
preview: Organization | null
|
||||
rules: RegionRule[]
|
||||
@@ -32,7 +39,45 @@ export function RegionMappingView(p: Props) {
|
||||
<button type="button" disabled={p.busy} onClick={p.onReload}>
|
||||
{p.dirty ? '放弃修改并重读' : '重新读取'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
p.busy ||
|
||||
p.dirty ||
|
||||
p.syncSubmitting ||
|
||||
!p.syncStatus?.configured ||
|
||||
!p.syncStatus.worker_ready ||
|
||||
directorySyncActive(p.syncStatus ?? null)
|
||||
}
|
||||
onClick={p.onSync}
|
||||
>
|
||||
同步通讯录
|
||||
</button>
|
||||
</div>
|
||||
<div className="qa-ops-muted" aria-label="通讯录后台同步状态" role="status">
|
||||
{!p.syncStatus
|
||||
? '正在读取后台同步状态…'
|
||||
: !p.syncStatus.configured
|
||||
? '后台同步未接线'
|
||||
: p.syncStatus.job
|
||||
? {
|
||||
pending: '等待后台执行器',
|
||||
running: '正在读取并校验通讯录',
|
||||
retry: '上次同步失败,等待后台重试;保留原快照',
|
||||
completed: '同步已完成,完整快照已落库',
|
||||
failed: '同步失败,保留原快照;可重新同步',
|
||||
cancelled: '同步已取消,保留原快照',
|
||||
}[p.syncStatus.job.state]
|
||||
: p.syncStatus.worker_ready
|
||||
? '后台执行器在线,尚未发起同步'
|
||||
: '后台执行器未在线,不会创建无人处理的任务'}
|
||||
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
|
||||
</div>
|
||||
{p.syncError ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{p.syncError}
|
||||
</p>
|
||||
) : null}
|
||||
{p.state?.directory_synced_at ? (
|
||||
<p className="qa-ops-muted">
|
||||
{p.state.directory_source === 'weekly_report_snapshot' ? '历史快照' : '全量同步快照'} · 通讯录同步时间:
|
||||
@@ -152,6 +197,14 @@ function signature(rules: RegionRule[]) {
|
||||
return JSON.stringify([...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)))
|
||||
}
|
||||
export function QARegions() {
|
||||
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
|
||||
[syncError, setSyncError] = useState(''),
|
||||
[syncSubmitting, setSyncSubmitting] = useState(false)
|
||||
const syncOperation = useRef(''),
|
||||
syncFlight = useRef(false),
|
||||
syncAction = useRef<AbortController | null>(null),
|
||||
lastCompleted = useRef(''),
|
||||
dirtyRef = useRef(false)
|
||||
const [state, setState] = useState<Organization | null>(null),
|
||||
[preview, setPreview] = useState<Organization | null>(null),
|
||||
[rules, setRules] = useState<RegionRule[]>([])
|
||||
@@ -176,7 +229,10 @@ export function QARegions() {
|
||||
setPreview(null)
|
||||
try {
|
||||
const value = await fetchOrganization(controller.signal)
|
||||
if (!controller.signal.aborted) accept(value)
|
||||
if (!controller.signal.aborted) {
|
||||
accept(value)
|
||||
return true
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '读取失败')
|
||||
} finally {
|
||||
@@ -187,6 +243,72 @@ export function QARegions() {
|
||||
void load()
|
||||
return () => request.current?.abort()
|
||||
}, [])
|
||||
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
|
||||
dirtyRef.current = dirty
|
||||
const loadRef = useRef(load)
|
||||
loadRef.current = load
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const poll = async () => {
|
||||
let delay = 10000
|
||||
try {
|
||||
const value = await fetchDirectorySync(controller.signal)
|
||||
if (controller.signal.aborted) return
|
||||
setSyncStatus(value)
|
||||
setSyncError('')
|
||||
delay = directorySyncActive(value) ? 1500 : 10000
|
||||
const job = value.job
|
||||
if (job?.state === 'completed' && job.id !== lastCompleted.current) {
|
||||
const action = completedSyncAction(value, lastCompleted.current, dirtyRef.current)
|
||||
lastCompleted.current = job.id
|
||||
if (action === 'preserve') setNotice('通讯录已同步,当前未保存草稿仍保留;请核对后重新读取')
|
||||
else if (action === 'reload' && (await loadRef.current())) setNotice('通讯录同步完成并已重新读取')
|
||||
} else if (job && lastCompleted.current === '') lastCompleted.current = 'pending:' + job.id
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setSyncError(e instanceof Error ? e.message : '同步状态读取失败,未将现有快照清空')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(() => void poll(), delay)
|
||||
}
|
||||
}
|
||||
void poll()
|
||||
return () => {
|
||||
controller.abort()
|
||||
clearTimeout(timer)
|
||||
syncAction.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
const synchronize = async () => {
|
||||
if (
|
||||
busy ||
|
||||
dirty ||
|
||||
syncFlight.current ||
|
||||
!syncStatus?.configured ||
|
||||
!syncStatus.worker_ready ||
|
||||
directorySyncActive(syncStatus)
|
||||
)
|
||||
return
|
||||
syncFlight.current = true
|
||||
setSyncSubmitting(true)
|
||||
setSyncError('')
|
||||
const controller = new AbortController()
|
||||
syncAction.current = controller
|
||||
try {
|
||||
if (!syncOperation.current) syncOperation.current = newOperationID()
|
||||
const receipt = await startDirectorySync(syncOperation.current, controller.signal)
|
||||
syncOperation.current = ''
|
||||
if (controller.signal.aborted) return
|
||||
lastCompleted.current = 'submitted:' + receipt.job_id
|
||||
setSyncStatus(await fetchDirectorySync(controller.signal))
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setSyncError(e instanceof Error ? e.message : '同步提交结果未知;重试会复用原操作标识')
|
||||
} finally {
|
||||
syncFlight.current = false
|
||||
if (!controller.signal.aborted) setSyncSubmitting(false)
|
||||
}
|
||||
}
|
||||
const edit = (next: RegionRule[]) => {
|
||||
setRules(next)
|
||||
setPreview(null)
|
||||
@@ -225,6 +347,10 @@ export function QARegions() {
|
||||
}
|
||||
return (
|
||||
<RegionMappingView
|
||||
syncStatus={syncStatus}
|
||||
syncError={syncError}
|
||||
syncSubmitting={syncSubmitting}
|
||||
onSync={() => void synchronize()}
|
||||
state={state}
|
||||
preview={preview}
|
||||
rules={rules}
|
||||
@@ -233,7 +359,7 @@ export function QARegions() {
|
||||
busy={busy}
|
||||
error={error}
|
||||
notice={notice}
|
||||
dirty={Boolean(state && signature(rules) !== signature(state.rules))}
|
||||
dirty={dirty}
|
||||
onRegion={setRegion}
|
||||
onSearch={setSearch}
|
||||
onToggle={(id, checked) => edit(changeRegionRule(rules, id, region, checked))}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { QAUsageView } from './QAUsage'
|
||||
import { parseQAUsage } from './qaUsage'
|
||||
const usage = parseQAUsage({
|
||||
organization: {
|
||||
state: 'ready',
|
||||
directory_id: 'd',
|
||||
directory_source: 'weekly_report_live',
|
||||
synced_at: '2026-10-17T07:59:50Z',
|
||||
revision_id: 'r',
|
||||
basis: 'current_directory',
|
||||
},
|
||||
as_of: '2026-10-17T08:00:00Z',
|
||||
start: '2026-10-14T00:00:00Z',
|
||||
end: '2026-10-15T00:00:00Z',
|
||||
keyword: '',
|
||||
questions: 2,
|
||||
identified_users: 0,
|
||||
rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }],
|
||||
})
|
||||
describe('usage statistics evidence', () => {
|
||||
it('shows a current-roster basis and unknown counts without performance claims', () => {
|
||||
const html = renderToStaticMarkup(<QAUsageView data={usage} loading={false} error="" onRetry={() => {}} />)
|
||||
expect(html).toContain('按当前通讯录回看')
|
||||
expect(html).toContain('名册未匹配')
|
||||
expect(html).toContain('不可确定')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).not.toContain('绩效合格')
|
||||
})
|
||||
it('keeps unavailable data an error, not a zero-result report', () => {
|
||||
const html = renderToStaticMarkup(<QAUsageView data={null} loading={false} error="上游不可用" onRetry={() => {}} />)
|
||||
expect(html).toContain('上游不可用')
|
||||
expect(html).not.toContain('共 0 条')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchQAUsage, usageLabels } from './qaUsage'
|
||||
import type { QAUsage as Usage } from './qaUsage'
|
||||
interface Props {
|
||||
data: Usage | null
|
||||
loading: boolean
|
||||
error: string
|
||||
onRetry: () => void
|
||||
}
|
||||
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { hour12: false })
|
||||
export function QAUsageView({ data, loading, error, onRetry }: Props) {
|
||||
return (
|
||||
<section className="qa-ops-results" aria-label="使用统计">
|
||||
<p className="qa-ops-slice-note">
|
||||
按当前通讯录回看历史问答,不代表提问时的组织归属。成功/失败是源端运行状态,不等于答案正确;不输出绩效结论。
|
||||
</p>
|
||||
{loading ? <p role="status">正在读取完整筛选范围的使用统计…</p> : null}
|
||||
{error ? (
|
||||
<p className="error-banner" role="alert">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={onRetry} disabled={loading}>
|
||||
重试统计
|
||||
</button>
|
||||
</p>
|
||||
) : null}
|
||||
{data && !error ? (
|
||||
<>
|
||||
<div className="qa-ops-result-bar">
|
||||
<span>
|
||||
共 {data.questions} 条问答 · 已关联提问人数 {data.identified_users}
|
||||
</span>
|
||||
<span>统计截止读取时间:{stamp(data.as_of)}</span>
|
||||
</div>
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束时刻)
|
||||
{data.keyword ? ` · 原问题包含:${data.keyword}` : ''}
|
||||
</p>
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
{data.organization.state === 'ready'
|
||||
? `通讯录同步:${stamp(data.organization.synced_at!)} · 目录 ${data.organization.directory_id} · 区域配置 ${data.organization.revision_id || '尚未保存'}`
|
||||
: '尚无完整通讯录,当前不能确定部门区域或去重人数。'}
|
||||
</p>
|
||||
<div className="qa-ops-table-scroll" tabIndex={0} aria-label="使用统计表格滚动区">
|
||||
<table className="qa-ops-table qa-usage-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>区域/待核对状态</th>
|
||||
<th>问答条数</th>
|
||||
<th>成功</th>
|
||||
<th>失败</th>
|
||||
<th>其他状态</th>
|
||||
<th>已关联提问人数</th>
|
||||
<th>通讯录归属人数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.rows.map((row) => (
|
||||
<tr key={row.key}>
|
||||
<td>{usageLabels[row.key]}</td>
|
||||
<td>{row.questions}</td>
|
||||
<td>{row.succeeded}</td>
|
||||
<td>{row.failed}</td>
|
||||
<td>{row.other}</td>
|
||||
<td>{row.users ?? '不可确定'}</td>
|
||||
<td>{row.roster_people ?? '不适用'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
按问答唯一 ID 计次;同一名册人员的多部门、多个身份记录只计 1
|
||||
人。未匹配或身份冲突不编造人数;通讯录人数不是在职或考核人数。
|
||||
</p>
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QAUsage({ query }: { query: QAQuery | null }) {
|
||||
const [data, setData] = useState<Usage | null>(null),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[revision, setRevision] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!query) return
|
||||
const c = new AbortController()
|
||||
setLoading(true)
|
||||
setData(null)
|
||||
setError('')
|
||||
void fetchQAUsage(query, c.signal)
|
||||
.then((value) => {
|
||||
if (!c.signal.aborted) setData(value)
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '统计读取失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!c.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [query, revision])
|
||||
return <QAUsageView data={data} loading={loading} error={error} onRetry={() => setRevision((v) => v + 1)} />
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseQAOrganizationVersion, mergeQAPages, parseQARecordPage } from './qaOps'
|
||||
import { parseQAUsage } from './qaUsage'
|
||||
const version = {
|
||||
state: 'ready',
|
||||
directory_id: 'd',
|
||||
directory_source: 'weekly_report_live',
|
||||
synced_at: '2026-10-17T07:59:50Z',
|
||||
revision_id: 'r',
|
||||
basis: 'current_directory',
|
||||
}
|
||||
const row = { key: 'APAC', questions: 5, succeeded: 3, failed: 1, other: 1, users: 1, roster_people: 4 }
|
||||
const usage = {
|
||||
organization: version,
|
||||
as_of: '2026-10-17T08:00:00Z',
|
||||
start: '2026-10-14T00:00:00Z',
|
||||
end: '2026-10-15T00:00:00Z',
|
||||
keyword: '',
|
||||
questions: 5,
|
||||
identified_users: 1,
|
||||
rows: [row],
|
||||
}
|
||||
describe('organization evidence and usage contracts', () => {
|
||||
it('keeps a valid current-roster version and rejects contradictory metadata', () => {
|
||||
expect(parseQAOrganizationVersion(version).directory_id).toBe('d')
|
||||
expect(() => parseQAOrganizationVersion({ ...version, directory_id: '' })).toThrow()
|
||||
})
|
||||
it('does not append pages across directory or regional revisions', () => {
|
||||
const page = parseQARecordPage({
|
||||
items: [],
|
||||
columns: [],
|
||||
total: 0,
|
||||
has_more: false,
|
||||
next_cursor: '',
|
||||
as_of: usage.as_of,
|
||||
organization: version,
|
||||
})
|
||||
expect(() =>
|
||||
mergeQAPages(page, { ...page, organization: { ...page.organization!, revision_id: 'changed' } })
|
||||
).toThrow(/配置已变化/)
|
||||
expect(mergeQAPages(page, page).total).toBe(0)
|
||||
})
|
||||
it('validates event conservation and unknown participant counts instead of inventing zeros', () => {
|
||||
expect(parseQAUsage(usage).identified_users).toBe(1)
|
||||
expect(parseQAUsage({ ...usage, rows: [{ ...row, users: null, roster_people: null }] }).rows[0].users).toBeNull()
|
||||
expect(() => parseQAUsage({ ...usage, questions: 6 })).toThrow()
|
||||
expect(() => parseQAUsage({ ...usage, rows: [{ ...row, other: 0 }] })).toThrow()
|
||||
expect(() => parseQAUsage({ ...usage, rows: [{ ...row, questions: -1 }] })).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -66,6 +66,12 @@
|
||||
outline: 2px solid var(--c-run);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.qa-ops-organization {
|
||||
margin: 8px 14px;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-ops-results {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
+93
-2
@@ -17,7 +17,59 @@ export const qaColumns = [
|
||||
] as const
|
||||
|
||||
export type QAColumn = (typeof qaColumns)[number]['key']
|
||||
export interface QAOrganizationVersion {
|
||||
state: 'ready' | 'empty'
|
||||
directory_id: string
|
||||
directory_source: string
|
||||
synced_at: string | null
|
||||
revision_id: string
|
||||
basis: 'current_directory'
|
||||
}
|
||||
export interface QARecordOrganization {
|
||||
version: QAOrganizationVersion
|
||||
state: string
|
||||
departments: string[]
|
||||
region: string
|
||||
source_department: string
|
||||
source_region: string
|
||||
department_origin: string
|
||||
region_origin: string
|
||||
}
|
||||
export function parseQAOrganizationVersion(value: unknown): QAOrganizationVersion {
|
||||
const v = object(value)
|
||||
if (!['ready', 'empty'].includes(text(v.state)) || v.basis !== 'current_directory') return invalid()
|
||||
const result = {
|
||||
state: v.state as QAOrganizationVersion['state'],
|
||||
directory_id: text(v.directory_id),
|
||||
directory_source: text(v.directory_source),
|
||||
synced_at: v.synced_at === null ? null : instant(v.synced_at),
|
||||
revision_id: text(v.revision_id),
|
||||
basis: 'current_directory' as const,
|
||||
}
|
||||
if (
|
||||
result.state === 'ready' &&
|
||||
(!result.directory_id ||
|
||||
!result.synced_at ||
|
||||
!['weekly_report_live', 'weekly_report_snapshot'].includes(result.directory_source))
|
||||
)
|
||||
return invalid()
|
||||
if (result.state === 'empty' && (result.directory_id || result.revision_id || result.synced_at !== null))
|
||||
return invalid()
|
||||
return result
|
||||
}
|
||||
export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecordPage {
|
||||
if (
|
||||
current.organization?.directory_id !== next.organization?.directory_id ||
|
||||
current.organization?.revision_id !== next.organization?.revision_id
|
||||
)
|
||||
throw new Error('通讯录或区域配置已变化,请重新查询,不能混合不同版本的分页结果')
|
||||
return {
|
||||
...next,
|
||||
items: [...current.items, ...next.items.filter((item) => !current.items.some((old) => old.id === item.id))],
|
||||
}
|
||||
}
|
||||
export interface QARecord {
|
||||
organization?: QARecordOrganization
|
||||
id: string
|
||||
status: string
|
||||
question: string
|
||||
@@ -41,6 +93,7 @@ export interface QARecord {
|
||||
language?: string
|
||||
}
|
||||
export interface QARecordPage {
|
||||
organization?: QAOrganizationVersion
|
||||
items: QARecord[]
|
||||
columns: QAColumn[]
|
||||
total: number
|
||||
@@ -121,6 +174,36 @@ export function parseQARecord(value: unknown): QARecord {
|
||||
if (typeof row.is_correct !== 'boolean' && row.is_correct !== null) return invalid()
|
||||
item.is_correct = row.is_correct
|
||||
}
|
||||
if (row.organization !== undefined) {
|
||||
const o = object(row.organization)
|
||||
if (
|
||||
!Array.isArray(o.departments) ||
|
||||
![
|
||||
'matched',
|
||||
'unassigned',
|
||||
'cross_region',
|
||||
'unmatched',
|
||||
'identity_conflict',
|
||||
'no_identity',
|
||||
'directory_missing',
|
||||
].includes(text(o.state))
|
||||
)
|
||||
return invalid()
|
||||
const origin = (v: unknown) => {
|
||||
const s = text(v)
|
||||
return ['source_snapshot', 'current_directory', 'unavailable'].includes(s) ? s : invalid()
|
||||
}
|
||||
item.organization = {
|
||||
version: parseQAOrganizationVersion(o.version),
|
||||
state: text(o.state),
|
||||
departments: o.departments.map(text),
|
||||
region: text(o.region),
|
||||
source_department: text(o.source_department),
|
||||
source_region: text(o.source_region),
|
||||
department_origin: origin(o.department_origin),
|
||||
region_origin: origin(o.region_origin),
|
||||
}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
@@ -137,10 +220,18 @@ export function parseQARecordPage(value: unknown): QARecordPage {
|
||||
return invalid()
|
||||
if (new Set(items.map(({ id }) => id)).size !== items.length || new Set(columns).size !== columns.length)
|
||||
return invalid()
|
||||
return { items, columns, total, has_more: page.has_more, next_cursor: nextCursor, as_of: instant(page.as_of) }
|
||||
return {
|
||||
items,
|
||||
columns,
|
||||
total,
|
||||
has_more: page.has_more,
|
||||
next_cursor: nextCursor,
|
||||
as_of: instant(page.as_of),
|
||||
...(page.organization === undefined ? {} : { organization: parseQAOrganizationVersion(page.organization) }),
|
||||
}
|
||||
}
|
||||
|
||||
async function getPayload(path: string, signal?: AbortSignal): Promise<unknown> {
|
||||
export async function getPayload(path: string, signal?: AbortSignal): Promise<unknown> {
|
||||
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal })
|
||||
const raw: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
|
||||
+5
-5
@@ -30,20 +30,20 @@ export interface Organization {
|
||||
missing_departments: string[]
|
||||
}
|
||||
}
|
||||
function invalid(): never {
|
||||
export function invalid(): never {
|
||||
throw new Error('通讯录或区域配置响应格式无效')
|
||||
}
|
||||
function obj(value: unknown): Record<string, unknown> {
|
||||
export function obj(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid()
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
function str(value: unknown): string {
|
||||
export function str(value: unknown): string {
|
||||
return typeof value === 'string' ? value : invalid()
|
||||
}
|
||||
function count(value: unknown): number {
|
||||
export function count(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : invalid()
|
||||
}
|
||||
function instant(value: unknown): string | null {
|
||||
export function instant(value: unknown): string | null {
|
||||
return value === null ? null : typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : invalid()
|
||||
}
|
||||
export function parseOrganization(value: unknown): Organization {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { parseDirectorySync, startDirectorySync, fetchDirectorySync, completedSyncAction } from './qaOrgSync'
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const idle = { configured: true, worker_ready: true, job: null }
|
||||
describe('directory synchronization contract', () => {
|
||||
it('reloads a completed job even on first observation, without replacing an unsaved draft', () => {
|
||||
const status = parseDirectorySync({
|
||||
...idle,
|
||||
job: {
|
||||
id: 'new-job',
|
||||
state: 'completed',
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T08:00:00Z',
|
||||
error_code: '',
|
||||
result: { directory_id: 'd', departments: 1, people: 1, synced_at: '2026-10-17T08:00:00Z' },
|
||||
},
|
||||
})
|
||||
expect(completedSyncAction(status, '', false)).toBe('reload')
|
||||
expect(completedSyncAction(status, '', true)).toBe('preserve')
|
||||
expect(completedSyncAction(status, 'new-job', false)).toBe('none')
|
||||
expect(completedSyncAction({ ...status, job: { ...status.job!, state: 'running' } }, '', false)).toBe('none')
|
||||
})
|
||||
it('keeps unknown/failed state distinct from empty data', () => {
|
||||
expect(parseDirectorySync(idle).job).toBeNull()
|
||||
expect(() => parseDirectorySync({ ...idle, worker_ready: 'yes' })).toThrow()
|
||||
expect(() => parseDirectorySync({ ...idle, job: { id: 'x', state: 'mystery' } })).toThrow()
|
||||
const result = { directory_id: 'd', departments: 327, people: 1534, synced_at: '2026-10-17T07:00:00Z' }
|
||||
const job = {
|
||||
id: 'j',
|
||||
state: 'completed',
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T07:01:00Z',
|
||||
error_code: '',
|
||||
result,
|
||||
}
|
||||
expect(parseDirectorySync({ ...idle, job }).job?.result?.people).toBe(1534)
|
||||
expect(() => parseDirectorySync({ ...idle, job: { ...job, result: { ...result, people: -1 } } })).toThrow()
|
||||
})
|
||||
it('sends a stable idempotency header and no tenant, credential or executable path', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: { job_id: 'j', deduplicated: false }, operation: 'replayed' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
expect((await startDirectorySync('same-action')).operation).toBe('replayed')
|
||||
expect(fetcher).toHaveBeenCalledWith(
|
||||
'/api/v1/qa-ops/organization/sync',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: '{}',
|
||||
headers: expect.objectContaining({
|
||||
'Idempotency-Key': 'same-action',
|
||||
'X-Governance-Action': 'qa-organization',
|
||||
}),
|
||||
})
|
||||
)
|
||||
})
|
||||
it('reads live job state and surfaces server failure instead of a successful empty result', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: idle }) })
|
||||
.mockResolvedValueOnce({ ok: false, status: 503, json: async () => ({ error: '执行器未在线' }) })
|
||||
)
|
||||
expect((await fetchDirectorySync()).worker_ready).toBe(true)
|
||||
await expect(startDirectorySync('same-action')).rejects.toThrow('执行器未在线')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
export interface DirectorySyncResult {
|
||||
directory_id: string
|
||||
departments: number
|
||||
people: number
|
||||
synced_at: string
|
||||
}
|
||||
export interface DirectorySyncJob {
|
||||
id: string
|
||||
state: 'pending' | 'running' | 'retry' | 'completed' | 'failed' | 'cancelled'
|
||||
attempt: number
|
||||
max_attempts: number
|
||||
updated_at: string
|
||||
error_code: string
|
||||
result: DirectorySyncResult | null
|
||||
}
|
||||
export interface DirectorySyncStatus {
|
||||
configured: boolean
|
||||
worker_ready: boolean
|
||||
job: DirectorySyncJob | null
|
||||
}
|
||||
export function completedSyncAction(
|
||||
s: DirectorySyncStatus,
|
||||
last: string,
|
||||
dirty: boolean
|
||||
): 'none' | 'preserve' | 'reload' {
|
||||
if (s.job?.state !== 'completed' || s.job.id === last) return 'none'
|
||||
return dirty ? 'preserve' : 'reload'
|
||||
}
|
||||
export const directorySyncActive = (s: DirectorySyncStatus | null) =>
|
||||
Boolean(s?.job && ['pending', 'running', 'retry'].includes(s.job.state))
|
||||
import { invalid as bad, obj as object, str as text, count, instant as nullableInstant } from './qaOrg'
|
||||
function instant(v: unknown): string {
|
||||
return nullableInstant(v) ?? bad()
|
||||
}
|
||||
export function parseDirectorySync(raw: unknown): DirectorySyncStatus {
|
||||
const s = object(raw)
|
||||
if (typeof s.configured !== 'boolean' || typeof s.worker_ready !== 'boolean') return bad()
|
||||
let job: DirectorySyncJob | null = null
|
||||
if (s.job !== null) {
|
||||
const j = object(s.job)
|
||||
if (!['pending', 'running', 'retry', 'completed', 'failed', 'cancelled'].includes(text(j.state))) return bad()
|
||||
let result: DirectorySyncResult | null = null
|
||||
if (j.result !== null) {
|
||||
const r = object(j.result)
|
||||
result = {
|
||||
directory_id: text(r.directory_id),
|
||||
departments: count(r.departments),
|
||||
people: count(r.people),
|
||||
synced_at: instant(r.synced_at),
|
||||
}
|
||||
if (!result.directory_id || !result.departments || !result.people) return bad()
|
||||
}
|
||||
job = {
|
||||
id: text(j.id),
|
||||
state: j.state as DirectorySyncJob['state'],
|
||||
attempt: count(j.attempt),
|
||||
max_attempts: count(j.max_attempts),
|
||||
updated_at: instant(j.updated_at),
|
||||
error_code: text(j.error_code),
|
||||
result,
|
||||
}
|
||||
if (!job.id || !job.max_attempts || job.attempt > job.max_attempts || (job.state === 'completed' && !result))
|
||||
return bad()
|
||||
}
|
||||
return { configured: s.configured, worker_ready: s.worker_ready, job }
|
||||
}
|
||||
async function request(method: string, operationID?: string, signal?: AbortSignal) {
|
||||
const response = await fetch('/api/v1/qa-ops/organization/sync', {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
headers:
|
||||
method === 'POST'
|
||||
? {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'qa-organization',
|
||||
'Idempotency-Key': operationID ?? '',
|
||||
}
|
||||
: undefined,
|
||||
body: method === 'POST' ? '{}' : undefined,
|
||||
})
|
||||
const raw: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
|
||||
throw new Error(typeof error === 'string' ? error : `通讯录同步请求失败(HTTP ${response.status})`)
|
||||
}
|
||||
return object(raw)
|
||||
}
|
||||
export async function fetchDirectorySync(signal?: AbortSignal) {
|
||||
return parseDirectorySync((await request('GET', undefined, signal)).data)
|
||||
}
|
||||
export async function startDirectorySync(operationID: string, signal?: AbortSignal) {
|
||||
if (!operationID || operationID.trim() !== operationID || operationID.length > 128) return bad()
|
||||
const envelope = await request('POST', operationID, signal),
|
||||
data = object(envelope.data)
|
||||
if (
|
||||
(envelope.operation !== 'created' && envelope.operation !== 'replayed') ||
|
||||
typeof data.deduplicated !== 'boolean' ||
|
||||
!text(data.job_id)
|
||||
)
|
||||
return bad()
|
||||
return { job_id: text(data.job_id), deduplicated: data.deduplicated, operation: envelope.operation }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { QAOrganizationVersion, QAQuery } from './qaOps'
|
||||
import { getPayload, parseQAOrganizationVersion } from './qaOps'
|
||||
export interface QAUsageRow {
|
||||
key: string
|
||||
questions: number
|
||||
succeeded: number
|
||||
failed: number
|
||||
other: number
|
||||
users: number | null
|
||||
roster_people: number | null
|
||||
}
|
||||
export interface QAUsage {
|
||||
organization: QAOrganizationVersion
|
||||
as_of: string
|
||||
start: string
|
||||
end: string
|
||||
keyword: string
|
||||
questions: number
|
||||
identified_users: number
|
||||
rows: QAUsageRow[]
|
||||
}
|
||||
const bad = (): never => {
|
||||
throw new Error('使用统计响应无效,请检查完整性及接口契约')
|
||||
}
|
||||
const obj = (v: unknown): Record<string, unknown> =>
|
||||
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
|
||||
const text = (v: unknown) => (typeof v === 'string' ? v : bad())
|
||||
const count = (v: unknown) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
|
||||
const stamp = (v: unknown) => {
|
||||
const s = text(v)
|
||||
return !Number.isNaN(Date.parse(s)) ? s : bad()
|
||||
}
|
||||
export const usageLabels: Record<string, string> = {
|
||||
国内工业: '国内工业',
|
||||
APAC: 'APAC',
|
||||
EMEA: 'EMEA',
|
||||
America: 'America',
|
||||
unassigned: '未配置区域',
|
||||
cross_region: '跨区域待核对',
|
||||
unmatched: '名册未匹配',
|
||||
identity_conflict: '身份冲突',
|
||||
no_identity: '身份信息缺失',
|
||||
directory_missing: '尚无完整通讯录',
|
||||
}
|
||||
export function parseQAUsage(value: unknown): QAUsage {
|
||||
const v = obj(value)
|
||||
if (!Array.isArray(v.rows)) return bad()
|
||||
const rows = v.rows.map((raw) => {
|
||||
const r = obj(raw)
|
||||
const key = text(r.key)
|
||||
if (!Object.hasOwn(usageLabels, key)) return bad()
|
||||
const row = {
|
||||
key,
|
||||
questions: count(r.questions),
|
||||
succeeded: count(r.succeeded),
|
||||
failed: count(r.failed),
|
||||
other: count(r.other),
|
||||
users: r.users === null ? null : count(r.users),
|
||||
roster_people: r.roster_people === null ? null : count(r.roster_people),
|
||||
}
|
||||
if (row.questions !== row.succeeded + row.failed + row.other) return bad()
|
||||
return row
|
||||
})
|
||||
const result = {
|
||||
organization: parseQAOrganizationVersion(v.organization),
|
||||
as_of: stamp(v.as_of),
|
||||
start: stamp(v.start),
|
||||
end: stamp(v.end),
|
||||
keyword: text(v.keyword),
|
||||
questions: count(v.questions),
|
||||
identified_users: count(v.identified_users),
|
||||
rows,
|
||||
}
|
||||
if (
|
||||
result.questions !== rows.reduce((n, r) => n + r.questions, 0) ||
|
||||
new Set(rows.map((r) => r.key)).size !== rows.length ||
|
||||
!(new Date(result.start) < new Date(result.end))
|
||||
)
|
||||
return bad()
|
||||
return result
|
||||
}
|
||||
export async function fetchQAUsage(query: QAQuery, signal?: AbortSignal): Promise<QAUsage> {
|
||||
const params = new URLSearchParams({ start: query.start, end: query.end, keyword: query.keyword })
|
||||
return parseQAUsage(await getPayload(`/api/v1/qa-ops/usage?${params}`, signal))
|
||||
}
|
||||
Reference in New Issue
Block a user