Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1738,6 +1738,9 @@ components:
trace:
type: string
description: 请求追踪 ID(X-Request-ID)
error_id:
type: string
description: 错误编号 `DI-<业务码>-<8位大写hex>`(如 DI-50000-3F7A2C9B),仅错误响应携带(成功信封 omitempty 不出现);供用户复制报障,可拿编号到后端 ERROR 日志反查。见 issue #222(R-97)。
data:
description: 业务数据;错误或无数据时为空对象 {},不为 null
HealthData:
Expand Down
18 changes: 16 additions & 2 deletions backend/internal/handler/datasource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"

Expand Down Expand Up @@ -157,14 +158,27 @@ func serve(r *gin.Engine, method, target, body string) *httptest.ResponseRecorde
return w
}

// errorIDJSONRe 匹配信封里的 error_id 字段(issue #222 R-97):DI-<业务码>-<8位大写hex>。
var errorIDJSONRe = regexp.MustCompile(`"error_id":"(DI-\d{5}-[0-9A-F]{8})",`)

// assertBody compares the full JSON response body byte-for-byte (ignoring a
// possible trailing newline), pinning the exact envelope contract
// {code, msg, trace, data} the datasource handlers currently emit.
// error_id 每次随机生成,从逐字节比对中剥出单独校验:错误信封必须携带
// 形状合法的编号,成功信封必须不带。
func assertBody(t *testing.T, w *httptest.ResponseRecorder, want string) {
t.Helper()
got := strings.TrimSpace(w.Body.String())
if got != want {
t.Fatalf("response body mismatch:\n got: %s\nwant: %s", got, want)
isError := !strings.Contains(got, `"code":20000`)
if isError && !errorIDJSONRe.MatchString(got) {
t.Fatalf("error envelope must carry a well-formed error_id, got: %s", got)
}
stripped := got
if m := errorIDJSONRe.FindString(got); m != "" {
stripped = strings.Replace(got, m, "", 1)
}
if stripped != want {
t.Fatalf("response body mismatch:\n got: %s\nwant: %s", stripped, want)
}
if w.Code != http.StatusOK {
t.Fatalf("expected HTTP status 200 (unified envelope), got %d", w.Code)
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/idls/gen_types.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 42 additions & 16 deletions backend/internal/response/response.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package response

import (
"crypto/rand"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"reflect"
"strings"
"time"

"github.com/gin-gonic/gin"
)
Expand All @@ -26,10 +32,40 @@ const (

// Response 统一响应结构
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Trace string `json:"trace"`
Data any `json:"data"`
Code int `json:"code"`
Msg string `json:"msg"`
Trace string `json:"trace"`
ErrorID string `json:"error_id,omitempty"`
Data any `json:"data"`
}

// newErrorID 生成可复制报障的错误编号:`DI-<业务码>-<8位大写hex>`(如 DI-50000-3F7A2C9B)。
// 只用于报障对账,不承载随机性之外的语义;每次错误响应都不同,可反查方式是拿编号
// 去后端日志里 grep(同一编号会出现在 ERROR 日志行中)。issue #222(R-97)。
func newErrorID(code int) string {
buf := make([]byte, 4)
if _, err := rand.Read(buf); err != nil {
// crypto/rand 失败极罕见;退化为时间纳秒兜底,保证编号始终存在。
return fmt.Sprintf("DI-%d-T%08X", code, uint64(time.Now().UnixNano())&0xFFFFFFFF)
}
return fmt.Sprintf("DI-%d-%s", code, strings.ToUpper(hex.EncodeToString(buf)))
}

// writeError 是所有错误响应的唯一出口:生成 error_id、存进 gin 上下文
// (供 R-96 access 日志 / R-98 Sentry tag 同源取用)、打一行 ERROR 日志、写响应。
func writeError(c *gin.Context, code int, msg string, data any) {
id := newErrorID(code)
trace := getTraceID(c)
c.Set("error_id", id)
// R-96(issue #221)的 access 日志合入后,ERROR 行应从这里取 error_id 保持同源。
slog.Error("request failed", "error_id", id, "code", code, "msg", msg, "request_id", trace)
c.JSON(http.StatusOK, Response{
Code: code,
Msg: msg,
Trace: trace,
ErrorID: id,
Data: normalizeResponseData(data),
})
}

// 获取请求追踪 ID
Expand Down Expand Up @@ -145,22 +181,12 @@ func SuccessWithMsg(c *gin.Context, data any, msg string) {

// Error 错误响应
func Error(c *gin.Context, code int, msg string) {
c.JSON(http.StatusOK, Response{
Code: code,
Msg: msg,
Trace: getTraceID(c),
Data: normalizeResponseData(nil),
})
writeError(c, code, msg, nil)
}

// ErrorWithData 带数据的错误响应
func ErrorWithData(c *gin.Context, code int, msg string, data any) {
c.JSON(http.StatusOK, Response{
Code: code,
Msg: msg,
Trace: getTraceID(c),
Data: normalizeResponseData(data),
})
writeError(c, code, msg, data)
}

// BadRequest 请求参数错误
Expand Down
82 changes: 82 additions & 0 deletions backend/internal/response/response_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package response

import (
"bytes"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"

"tablewave/internal/query"
Expand Down Expand Up @@ -91,3 +96,80 @@ func TestErrorUsesEmptyObjectData(t *testing.T) {
t.Fatalf("expected error data to be JSON object, got %T", payload["data"])
}
}

// errorIDPattern 是 issue #222(R-97)钉死的错误编号形状:DI-<业务码>-<8位大写hex>。
var errorIDPattern = regexp.MustCompile(`^DI-\d{5}-[0-9A-F]{8}$`)

// TestErrorResponseCarriesErrorID verifies every error response carries a well-formed
// error_id, the same id is stashed in the gin context for R-96/R-98 to pick up, and
// consecutive errors get distinct ids (报障编号必须可区分两次失败).
func TestErrorResponseCarriesErrorID(t *testing.T) {
for _, fn := range []struct {
name string
call func(c *gin.Context)
}{
{"Error", func(c *gin.Context) { Error(c, CodeBadRequest, "bad") }},
{"ErrorWithData", func(c *gin.Context) { ErrorWithData(c, CodeInternalError, "boom", nil) }},
{"BadRequest", func(c *gin.Context) { BadRequest(c, "bad request") }},
{"InternalError", func(c *gin.Context) { InternalError(c, "internal") }},
} {
t.Run(fn.name, func(t *testing.T) {
ctx, recorder := newTestContext()

fn.call(ctx)

payload := decodeRecorderBody(t, recorder)
id, _ := payload["error_id"].(string)
if !errorIDPattern.MatchString(id) {
t.Fatalf("expected error_id matching %s, got %q", errorIDPattern, id)
}
if id != ctx.GetString("error_id") {
t.Fatalf("context error_id %q != body error_id %q", ctx.GetString("error_id"), id)
}
// 编号含业务码,可反查:DI-50000-… 对应 50000。
codeInt := int(payload["code"].(float64))
if want := fmt.Sprintf("DI-%d-", codeInt); !strings.HasPrefix(id, want) {
t.Fatalf("error_id %q should start with %q", id, want)
}
})
}

ctxA, _ := newTestContext()
ctxB, _ := newTestContext()
Error(ctxA, CodeInternalError, "first")
Error(ctxB, CodeInternalError, "second")
if ctxA.GetString("error_id") == ctxB.GetString("error_id") {
t.Fatalf("expected distinct error ids, got %q twice", ctxA.GetString("error_id"))
}
}

// TestSuccessOmitsErrorID verifies the success envelope stays clean: error_id is omitempty
// and must not appear on 20000 responses (前端只在失败分型里读它).
func TestSuccessOmitsErrorID(t *testing.T) {
ctx, recorder := newTestContext()

Success(ctx, map[string]string{"ok": "yes"})

payload := decodeRecorderBody(t, recorder)
if _, ok := payload["error_id"]; ok {
t.Fatalf("success envelope must not carry error_id, got %v", payload["error_id"])
}
}

// TestErrorLogsSameErrorID verifies the ERROR log line emitted at the response boundary
// carries the exact error_id returned in the envelope(issue #222 验收 6:响应与日志同源).
func TestErrorLogsSameErrorID(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
t.Cleanup(func() { slog.SetDefault(prev) })

ctx, recorder := newTestContext()
Error(ctx, CodeInternalError, "boom")

payload := decodeRecorderBody(t, recorder)
id, _ := payload["error_id"].(string)
if !strings.Contains(buf.String(), "error_id="+id) {
t.Fatalf("expected log line to contain error_id=%s, log was: %s", id, buf.String())
}
}
10 changes: 7 additions & 3 deletions frontend/src/__tests__/pages/ChartBuilder.comparison.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { render, screen, waitFor } from '@testing-library/react';
import type { AxiosResponse } from 'axios';
import { IntlProvider } from 'react-intl';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { chartsApi, datasetsApi } from '../../api';
import { messages } from '../../i18n/useLocale';
import type { ApiResponse } from '../../lib/api/client';
import ChartBuilder, { composeChartQueryRequest } from '../../pages/ChartBuilder';
import type { QueryConfig } from '../../store';
Expand Down Expand Up @@ -227,9 +229,11 @@ const seedApis = (config: string) => {

const renderBuilder = () =>
render(
<MemoryRouter initialEntries={['/chart-builder?edit=7&datasetId=1']}>
<ChartBuilder />
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={['/chart-builder?edit=7&datasetId=1']}>
<ChartBuilder />
</MemoryRouter>
</IntlProvider>
);

describe('ChartBuilder 同环比卡片(恢复已存图表)', () => {
Expand Down
14 changes: 9 additions & 5 deletions frontend/src/__tests__/pages/ChartBuilder.dragOverlay.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { AxiosResponse } from 'axios';
import { IntlProvider } from 'react-intl';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { chartsApi, datasetsApi } from '../../api';
import { messages } from '../../i18n/useLocale';
import type { ApiResponse } from '../../lib/api/client';
import ChartBuilder from '../../pages/ChartBuilder';
import { useStore } from '../../store';
Expand Down Expand Up @@ -106,11 +108,13 @@ const resetChartBuilderState = (): void => {
*/
const renderChartBuilder = () => {
return render(
<MemoryRouter initialEntries={['/chart-builder?edit=1&datasetId=1']}>
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={['/chart-builder?edit=1&datasetId=1']}>
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
</IntlProvider>
);
};

Expand Down
44 changes: 26 additions & 18 deletions frontend/src/__tests__/pages/ChartBuilder.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { AxiosResponse } from 'axios';
import { type ReactNode, StrictMode } from 'react';
import { IntlProvider } from 'react-intl';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { QueryRecord } from '../../api';
import { chartsApi, datasetsApi, datasourcesApi, queriesApi } from '../../api';
import { messages } from '../../i18n/useLocale';
import type { ApiResponse } from '../../lib/api/client';
import type { ChartConfigDocument } from '../../lib/chartConfigSchema';
import ChartBuilder from '../../pages/ChartBuilder';
Expand Down Expand Up @@ -160,23 +162,27 @@ const resetChartBuilderState = () => {

const renderChartBuilder = () => {
return render(
<MemoryRouter initialEntries={['/chart-builder?edit=1&datasetId=1']}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={['/chart-builder?edit=1&datasetId=1']}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
</IntlProvider>
);
};

const renderNewChartBuilder = () => {
return render(
<MemoryRouter initialEntries={['/chart-builder?datasetId=1']}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={['/chart-builder?datasetId=1']}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
</IntlProvider>
);
};

Expand All @@ -188,12 +194,14 @@ const renderNewChartBuilder = () => {
*/
const renderQueryRecordBuilder = (shortId: string, extraQuery = '', strict = false) => {
const tree = (
<MemoryRouter initialEntries={[`/chart-builder?q=${shortId}${extraQuery}`]}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={[`/chart-builder?q=${shortId}${extraQuery}`]}>
<LocationProbe />
<Routes>
<Route path="/chart-builder" element={<ChartBuilder />} />
</Routes>
</MemoryRouter>
</IntlProvider>
);
return render(strict ? <StrictMode>{tree}</StrictMode> : tree);
};
Expand Down
10 changes: 7 additions & 3 deletions frontend/src/__tests__/pages/ChartBuilder.topN.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { AxiosResponse } from 'axios';
import { IntlProvider } from 'react-intl';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { chartsApi, datasetsApi } from '../../api';
import { messages } from '../../i18n/useLocale';
import type { ApiResponse } from '../../lib/api/client';
import ChartBuilder, { composeChartQueryRequest } from '../../pages/ChartBuilder';
import type { QueryConfig } from '../../store';
Expand Down Expand Up @@ -213,9 +215,11 @@ const seedApis = (config: string) => {

const renderBuilder = () =>
render(
<MemoryRouter initialEntries={['/chart-builder?edit=8&datasetId=1']}>
<ChartBuilder />
</MemoryRouter>
<IntlProvider locale="zh-CN" messages={messages['zh-CN']}>
<MemoryRouter initialEntries={['/chart-builder?edit=8&datasetId=1']}>
<ChartBuilder />
</MemoryRouter>
</IntlProvider>
);

describe('ChartBuilder Top N 卡片(恢复已存图表)', () => {
Expand Down
Loading
Loading