feat: sync DingTalk QA to Notable question table
This commit is contained in:
@@ -0,0 +1,303 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Default DingTalk API base.
|
||||
const defaultBase = "https://api.dingtalk.com"
|
||||
|
||||
// Config holds the required parameters for the DingTalk question-table client.
|
||||
type Config struct {
|
||||
ClientID string
|
||||
Secret string
|
||||
BaseID string
|
||||
SheetID string
|
||||
OperatorID string
|
||||
|
||||
// TokenURL overrides the token endpoint. Empty → default.
|
||||
TokenURL string
|
||||
// BaseURL overrides the API base. Empty → default.
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
// defaultTransport is a clone of http.DefaultTransport with Proxy=nil so the
|
||||
// default client never uses a proxy (even from env). Shared across clients.
|
||||
var defaultTransport = func() *http.Transport {
|
||||
dt, ok := http.DefaultTransport.(*http.Transport)
|
||||
if !ok {
|
||||
return &http.Transport{
|
||||
Proxy: nil,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
}
|
||||
// Clone, then clear Proxy.
|
||||
clone := dt.Clone()
|
||||
clone.Proxy = nil
|
||||
return clone
|
||||
}()
|
||||
|
||||
// Client is a stdlib-only DingTalk HTTP client that inserts records into a
|
||||
// Notable v1 base. It owns a mutex-protected in-memory access-token cache.
|
||||
type Client struct {
|
||||
clientID string
|
||||
secret string
|
||||
baseID string
|
||||
sheetID string
|
||||
operatorID string
|
||||
|
||||
tokenURL string
|
||||
baseURL string
|
||||
|
||||
http *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
tokenExp time.Time
|
||||
}
|
||||
|
||||
// NewClient creates a validated Client. It returns an error when any of
|
||||
// clientID, secret, baseID, sheetID, or operatorID is empty.
|
||||
// httpClient may be nil; a default is used in that case.
|
||||
func NewClient(cfg Config, httpClient *http.Client) (*Client, error) {
|
||||
// Trim and validate.
|
||||
clientID := strings.TrimSpace(cfg.ClientID)
|
||||
if clientID == "" {
|
||||
return nil, errors.New("questiontable: client id is required")
|
||||
}
|
||||
secret := strings.TrimSpace(cfg.Secret)
|
||||
if secret == "" {
|
||||
return nil, errors.New("questiontable: secret is required")
|
||||
}
|
||||
baseID := strings.TrimSpace(cfg.BaseID)
|
||||
if baseID == "" {
|
||||
return nil, errors.New("questiontable: base id is required")
|
||||
}
|
||||
sheetID := strings.TrimSpace(cfg.SheetID)
|
||||
if sheetID == "" {
|
||||
return nil, errors.New("questiontable: sheet id is required")
|
||||
}
|
||||
operatorID := strings.TrimSpace(cfg.OperatorID)
|
||||
if operatorID == "" {
|
||||
return nil, errors.New("questiontable: operator id is required")
|
||||
}
|
||||
|
||||
if httpClient == nil {
|
||||
httpClient = &http.Client{
|
||||
Transport: defaultTransport,
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
tokenURL := strings.TrimSpace(cfg.TokenURL)
|
||||
if tokenURL == "" {
|
||||
tokenURL = defaultBase + "/v1.0/oauth2/accessToken"
|
||||
}
|
||||
baseURL := strings.TrimSpace(cfg.BaseURL)
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBase
|
||||
}
|
||||
|
||||
return &Client{
|
||||
clientID: clientID,
|
||||
secret: secret,
|
||||
baseID: baseID,
|
||||
sheetID: sheetID,
|
||||
operatorID: operatorID,
|
||||
tokenURL: tokenURL,
|
||||
baseURL: baseURL,
|
||||
http: httpClient,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TokenURL returns the configured token URL (test seam).
|
||||
func (c *Client) TokenURL() string { return c.tokenURL }
|
||||
|
||||
// BaseURL returns the configured API base (test seam).
|
||||
func (c *Client) BaseURL() string { return c.baseURL }
|
||||
|
||||
// insertRecordReq is the JSON body for the Notable v1 insertRecord endpoint.
|
||||
type insertRecordReq struct {
|
||||
Records []map[string]interface{} `json:"records"`
|
||||
}
|
||||
|
||||
// insertRecordResp is the success response body.
|
||||
type insertRecordResp struct {
|
||||
Value []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"value"`
|
||||
}
|
||||
|
||||
// tokenResp is the access-token response body.
|
||||
type tokenResp struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireIn int64 `json:"expireIn"`
|
||||
}
|
||||
|
||||
// InsertRecord sends a single row to the DingTalk Notable v1 base.
|
||||
// It returns the record ID on success.
|
||||
func (c *Client) InsertRecord(ctx context.Context, row Row) (string, error) {
|
||||
token, err := c.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable token: %w", err)
|
||||
}
|
||||
|
||||
path := fmt.Sprintf("/v1.0/notable/bases/%s/sheets/%s/records",
|
||||
url.PathEscape(c.baseID), url.PathEscape(c.sheetID))
|
||||
reqURL := c.baseURL + path + "?operatorId=" + url.QueryEscape(c.operatorID)
|
||||
|
||||
fields := row.ToFields()
|
||||
body := insertRecordReq{Records: []map[string]interface{}{fields}}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable marshal: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-acs-dingtalk-access-token", token)
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", safeDoErr(ctx, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read bounded response body.
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("questiontable insert returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var ir insertRecordResp
|
||||
if err := json.Unmarshal(raw, &ir); err != nil {
|
||||
return "", fmt.Errorf("questiontable decode response: %w", err)
|
||||
}
|
||||
if len(ir.Value) == 0 {
|
||||
return "", errors.New("questiontable empty value list")
|
||||
}
|
||||
if strings.TrimSpace(ir.Value[0].ID) == "" {
|
||||
return "", errors.New("questiontable empty record id")
|
||||
}
|
||||
|
||||
return ir.Value[0].ID, nil
|
||||
}
|
||||
|
||||
// safeDoErr wraps an http.Do error without exposing the raw URL or credentials.
|
||||
// If the context is already done, returns a wrapped ctx.Err() so errors.Is works.
|
||||
func safeDoErr(ctx context.Context, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("questiontable insert: %w", ctx.Err())
|
||||
}
|
||||
return errors.New("questiontable insert: network error")
|
||||
}
|
||||
|
||||
// getAccessToken returns a cached token or fetches a new one.
|
||||
func (c *Client) getAccessToken(ctx context.Context) (string, error) {
|
||||
c.mu.Lock()
|
||||
if c.token != "" && time.Now().Before(c.tokenExp) {
|
||||
tok := c.token
|
||||
c.mu.Unlock()
|
||||
return tok, nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
return c.fetchToken(ctx)
|
||||
}
|
||||
|
||||
// fetchToken calls the DingTalk OAuth2 endpoint and caches the result.
|
||||
func (c *Client) fetchToken(ctx context.Context) (string, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
// Double-check inside lock.
|
||||
if c.token != "" && time.Now().Before(c.tokenExp) {
|
||||
return c.token, nil
|
||||
}
|
||||
|
||||
body := map[string]string{
|
||||
"appKey": c.clientID,
|
||||
"appSecret": c.secret,
|
||||
}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable token marshal: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.tokenURL, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable token request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", safeTokenDoErr(ctx, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable token read: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("questiontable token returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var tr tokenResp
|
||||
if err := json.Unmarshal(raw, &tr); err != nil {
|
||||
return "", fmt.Errorf("questiontable token decode: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(tr.AccessToken) == "" {
|
||||
return "", errors.New("questiontable empty access token")
|
||||
}
|
||||
|
||||
// Token expiry must never be extended beyond DingTalk's expireIn.
|
||||
if tr.ExpireIn <= 0 {
|
||||
return "", errors.New("questiontable token: non-positive expireIn")
|
||||
}
|
||||
|
||||
exp := time.Duration(tr.ExpireIn) * time.Second
|
||||
// For very short TTL (<=30s), cache for a positive fraction (TTL/2).
|
||||
if exp <= 30*time.Second {
|
||||
exp = exp / 2
|
||||
} else {
|
||||
// Safety margin: subtract 30 seconds from expiry.
|
||||
exp -= 30 * time.Second
|
||||
}
|
||||
|
||||
c.token = tr.AccessToken
|
||||
c.tokenExp = time.Now().Add(exp)
|
||||
|
||||
return c.token, nil
|
||||
}
|
||||
|
||||
// safeTokenDoErr wraps an http.Do error from token fetch without exposing raw URL or credentials.
|
||||
func safeTokenDoErr(ctx context.Context, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("questiontable token: %w", ctx.Err())
|
||||
}
|
||||
return errors.New("questiontable token: network error")
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewClientRejectsMissingConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg Config
|
||||
}{
|
||||
{"empty client id", Config{Secret: "s", BaseID: "b", SheetID: "sh", OperatorID: "op"}},
|
||||
{"empty secret", Config{ClientID: "c", BaseID: "b", SheetID: "sh", OperatorID: "op"}},
|
||||
{"empty base id", Config{ClientID: "c", Secret: "s", SheetID: "sh", OperatorID: "op"}},
|
||||
{"empty sheet id", Config{ClientID: "c", Secret: "s", BaseID: "b", OperatorID: "op"}},
|
||||
{"empty operator id", Config{ClientID: "c", Secret: "s", BaseID: "b", SheetID: "sh"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
_, err := NewClient(tt.cfg, nil)
|
||||
if err == nil {
|
||||
t.Errorf("%s: expected error, got nil", tt.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordMethodPathHeaderBody(t *testing.T) {
|
||||
var (
|
||||
gotMethod string
|
||||
gotPath string
|
||||
gotQuery string
|
||||
gotToken string
|
||||
gotBody string
|
||||
tokenCalls int32
|
||||
insertCalls int32
|
||||
)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&tokenCalls, 1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"test-access-token","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&insertCalls, 1)
|
||||
gotMethod = r.Method
|
||||
gotPath = r.URL.Path
|
||||
gotQuery = r.URL.RawQuery
|
||||
gotToken = r.Header.Get("x-acs-dingtalk-access-token")
|
||||
|
||||
var body insertRecordReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode body: %v", err)
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
gotBody = string(raw)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"value":[{"id":"rec-abc-123"}]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "appKey-1",
|
||||
Secret: "appSecret-1",
|
||||
BaseID: "b1",
|
||||
SheetID: "sh1",
|
||||
OperatorID: "operator-1",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken",
|
||||
BaseURL: server.URL,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
|
||||
row := Row{
|
||||
Question: "测试问题",
|
||||
Answer: "测试答案",
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "union-zhang-san",
|
||||
}
|
||||
recID, err := client.InsertRecord(context.Background(), row)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertRecord: %v", err)
|
||||
}
|
||||
if recID != "rec-abc-123" {
|
||||
t.Errorf("recordID = %q, want %q", recID, "rec-abc-123")
|
||||
}
|
||||
|
||||
// Assert method, path, header, token.
|
||||
if gotMethod != http.MethodPost {
|
||||
t.Errorf("method = %q, want POST", gotMethod)
|
||||
}
|
||||
if gotPath != "/v1.0/notable/bases/b1/sheets/sh1/records" {
|
||||
t.Errorf("path = %q", gotPath)
|
||||
}
|
||||
if gotToken != "test-access-token" {
|
||||
t.Errorf("token header = %q, want test-access-token", gotToken)
|
||||
}
|
||||
|
||||
// operatorId must be in query only.
|
||||
if !strings.Contains(gotQuery, "operatorId=operator-1") {
|
||||
t.Errorf("query missing operatorId: %q", gotQuery)
|
||||
}
|
||||
|
||||
// body must NOT contain operatorId.
|
||||
if strings.Contains(gotBody, "operatorId") {
|
||||
t.Errorf("body contains operatorId: %q", gotBody)
|
||||
}
|
||||
|
||||
// body must contain typed field IDs.
|
||||
if !strings.Contains(gotBody, `"ZaMZF6j"`) {
|
||||
t.Errorf("body missing field ID ZaMZF6j: %q", gotBody)
|
||||
}
|
||||
if !strings.Contains(gotBody, `"Y4cpmxU"`) {
|
||||
t.Errorf("body missing field ID Y4cpmxU: %q", gotBody)
|
||||
}
|
||||
|
||||
// body must NOT contain the omitted select fields.
|
||||
omitted := []string{"QMn9UoU", "H3gtTuv", "nFvv8OR", "UMqUPAG", "lnF7gF9"}
|
||||
for _, fid := range omitted {
|
||||
if strings.Contains(gotBody, fid) {
|
||||
t.Errorf("body contains omitted select field %q: %q", fid, gotBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCacheTwoInsertsOneTokenCall(t *testing.T) {
|
||||
var tokenCalls int32
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&tokenCalls, 1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"cached-token","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("x-acs-dingtalk-access-token") != "cached-token" {
|
||||
t.Errorf("unexpected token on insert")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"value":[{"id":"rec-1"}]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "appKey-1",
|
||||
Secret: "appSecret-1",
|
||||
BaseID: "b1",
|
||||
SheetID: "sh1",
|
||||
OperatorID: "operator-1",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken",
|
||||
BaseURL: server.URL,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
|
||||
// Two inserts, only one token call.
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := client.InsertRecord(context.Background(), row); err != nil {
|
||||
t.Fatalf("InsertRecord %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
if tokenCalls != 1 {
|
||||
t.Errorf("token calls = %d, want 1", tokenCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordNon2xx(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"code":"invalid","message":"bad request"}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-2xx")
|
||||
}
|
||||
|
||||
// Error must not contain token, secret, operator, or raw row values.
|
||||
errStr := err.Error()
|
||||
for _, secret := range []string{"tok", "op", "union-x"} {
|
||||
if strings.Contains(errStr, secret) {
|
||||
t.Errorf("error redaction failed: %q found in %q", secret, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordMalformedResponse(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`not json`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for malformed response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordEmptyValueList(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"value":[]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty value list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordEmptyRecordID(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"value":[{"id":""}]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty record id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCallErrorRedaction(t *testing.T) {
|
||||
// Token endpoint returns non-2xx.
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"code":"unauthorized","message":"invalid appSecret"}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for token failure")
|
||||
}
|
||||
|
||||
// Error must not contain raw body, secret, or token.
|
||||
errStr := err.Error()
|
||||
for _, secret := range []string{"appSecret", "invalid appSecret", "unauthorized"} {
|
||||
if strings.Contains(errStr, secret) {
|
||||
t.Errorf("error redaction failed: %q found in %q", secret, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenEmptyAccessToken(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"","expireIn":7200}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty access token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenExpirySafetyMargin(t *testing.T) {
|
||||
// Token with expireIn=1: TTL ≤ 30s → exp = TTL/2 (500ms). The tokenExp
|
||||
// must be after now but no later than server expiry (1s) + small scheduling
|
||||
// tolerance. An immediate second request should still reuse the cache.
|
||||
var tokenCalls int32
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&tokenCalls, 1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"short-token","expireIn":1}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"value":[{"id":"rec-1"}]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
|
||||
// First call: token fetch.
|
||||
before := time.Now()
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err != nil {
|
||||
t.Fatalf("first InsertRecord: %v", err)
|
||||
}
|
||||
if tokenCalls != 1 {
|
||||
t.Errorf("token calls after first insert = %d, want 1", tokenCalls)
|
||||
}
|
||||
|
||||
// Inspect tokenExp.
|
||||
client.mu.Lock()
|
||||
exp := client.tokenExp
|
||||
client.mu.Unlock()
|
||||
|
||||
// tokenExp must be after now.
|
||||
if !exp.After(before) {
|
||||
t.Errorf("tokenExp %v is not after request start %v", exp, before)
|
||||
}
|
||||
// tokenExp must not exceed server expiry (1s) + scheduling tolerance (500ms).
|
||||
if exp.After(before.Add(1500 * time.Millisecond)) {
|
||||
t.Errorf("tokenExp %v exceeds server expiry + tolerance", exp)
|
||||
}
|
||||
|
||||
// Second call: should use cached token (within TTL/2 = 500ms).
|
||||
_, err = client.InsertRecord(context.Background(), row)
|
||||
if err != nil {
|
||||
t.Fatalf("second InsertRecord: %v", err)
|
||||
}
|
||||
if tokenCalls != 1 {
|
||||
t.Errorf("token calls after second insert = %d, want 1 (cached)", tokenCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenExpiryNonPositive(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":0}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, nil)
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-positive expireIn")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextTimeout(t *testing.T) {
|
||||
handlerDone := make(chan struct{})
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
// Wait for context cancellation or test signal.
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
case <-handlerDone:
|
||||
}
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
defer close(handlerDone) // runs before server.Close (LIFO), unblocks the handler
|
||||
|
||||
// Use a client with keep-alives disabled so the TCP connection
|
||||
// closes after the handler returns — httptest.Server.Close won't hang.
|
||||
httpClient := &http.Client{
|
||||
Transport: &http.Transport{DisableKeepAlives: true},
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL,
|
||||
}, httpClient)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(ctx, row)
|
||||
if err == nil {
|
||||
t.Fatal("expected timeout error")
|
||||
}
|
||||
if !errors.Is(err, context.DeadlineExceeded) && !strings.Contains(err.Error(), "context deadline") {
|
||||
t.Logf("timeout error (may be wrapped): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultURLs(t *testing.T) {
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
if client.TokenURL() != defaultBase+"/v1.0/oauth2/accessToken" {
|
||||
t.Errorf("default token URL = %q, want %q", client.TokenURL(), defaultBase+"/v1.0/oauth2/accessToken")
|
||||
}
|
||||
if client.BaseURL() != defaultBase {
|
||||
t.Errorf("default base URL = %q, want %q", client.BaseURL(), defaultBase)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomURLs(t *testing.T) {
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: "https://custom.example.com/token",
|
||||
BaseURL: "https://custom.example.com",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
if client.TokenURL() != "https://custom.example.com/token" {
|
||||
t.Errorf("custom token URL = %q", client.TokenURL())
|
||||
}
|
||||
if client.BaseURL() != "https://custom.example.com" {
|
||||
t.Errorf("custom base URL = %q", client.BaseURL())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientNilHTTP(t *testing.T) {
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient with nil http: %v", err)
|
||||
}
|
||||
if client.http == nil {
|
||||
t.Fatal("http client is nil after construction with nil argument")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientCustomHTTP(t *testing.T) {
|
||||
custom := &http.Client{Timeout: 5 * time.Second}
|
||||
client, err := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
}, custom)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient with custom http: %v", err)
|
||||
}
|
||||
if client.http != custom {
|
||||
t.Fatal("http client is not the custom one")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultTransportNoProxy(t *testing.T) {
|
||||
// The default transport must have Proxy=nil.
|
||||
if defaultTransport.Proxy != nil {
|
||||
t.Error("defaultTransport Proxy is not nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertRecordDoErrorRedaction(t *testing.T) {
|
||||
// Custom RoundTripper that returns an error containing secrets.
|
||||
secretErr := errors.New("connect: dial tcp https://api.dingtalk.com?operatorId=secret-op failed: row data union-x")
|
||||
rt := &errorRoundTripper{err: secretErr}
|
||||
|
||||
client, _ := NewClient(Config{
|
||||
ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op",
|
||||
TokenURL: "https://token.example.com", BaseURL: "https://api.example.com",
|
||||
}, &http.Client{Transport: rt})
|
||||
|
||||
row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}
|
||||
_, err := client.InsertRecord(context.Background(), row)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
|
||||
errStr := err.Error()
|
||||
for _, secret := range []string{"secret-op", "union-x", "api.dingtalk.com"} {
|
||||
if strings.Contains(strings.ToLower(errStr), strings.ToLower(secret)) {
|
||||
t.Errorf("error redaction failed: %q found in %q", secret, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// errorRoundTripper returns a fixed error on every RoundTrip.
|
||||
type errorRoundTripper struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (rt *errorRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return nil, rt.err
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FailureCodeRemoteInsertFailed is the stable public failure code used when
|
||||
// InsertRecord returns an error. The raw error is never persisted or returned.
|
||||
const FailureCodeRemoteInsertFailed = "remote_question_table_insert_failed"
|
||||
|
||||
// PendingExport is a row waiting to be exported to the remote question table.
|
||||
type PendingExport struct {
|
||||
ExportID string
|
||||
Row Row
|
||||
Attempts int
|
||||
}
|
||||
|
||||
// ExportRepository is the persistence contract for the background dispatcher.
|
||||
type ExportRepository interface {
|
||||
// Claim returns up to limit pending exports whose attempt count is below
|
||||
// maxAttempts and whose last claim time is before staleBefore.
|
||||
Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error)
|
||||
|
||||
// MarkExported records the location (Notable record ID) for a successfully exported row.
|
||||
MarkExported(ctx context.Context, exportID, location string) error
|
||||
|
||||
// MarkFailed records a failure for the given exportID with a stable failure code.
|
||||
MarkFailed(ctx context.Context, exportID, failureCode string) error
|
||||
}
|
||||
|
||||
// RecordInserter is the contract for inserting a row to the remote Notable base.
|
||||
// *Client.InsertRecord satisfies this interface.
|
||||
type RecordInserter interface {
|
||||
InsertRecord(ctx context.Context, row Row) (string, error)
|
||||
}
|
||||
|
||||
// DispatcherStats holds the outcome counters for a single RunOnce invocation.
|
||||
type DispatcherStats struct {
|
||||
Claimed int
|
||||
Exported int
|
||||
Failed int
|
||||
}
|
||||
|
||||
// DispatcherOptions holds optional configuration for the Dispatcher.
|
||||
type DispatcherOptions struct {
|
||||
Batch int
|
||||
MaxAttempts int
|
||||
ClaimLease time.Duration
|
||||
SendTimeout time.Duration
|
||||
}
|
||||
|
||||
// Dispatcher runs the background dispatch loop that claims pending exports
|
||||
// and inserts them to the remote question table.
|
||||
type Dispatcher struct {
|
||||
repo ExportRepository
|
||||
inserter RecordInserter
|
||||
|
||||
batch int
|
||||
maxAttempts int
|
||||
claimLease time.Duration
|
||||
sendTimeout time.Duration
|
||||
}
|
||||
|
||||
// isNil reports whether x is nil. It accepts any value and only calls
|
||||
// IsNil when the underlying kind is nil-able. Value types (structs, ints,
|
||||
// strings, etc.) are never nil and return false without panicking.
|
||||
func isNil(x interface{}) bool {
|
||||
if x == nil {
|
||||
return true
|
||||
}
|
||||
v := reflect.ValueOf(x)
|
||||
switch v.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
||||
return v.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// NewDispatcher creates a validated Dispatcher. It returns an error when repo
|
||||
// or inserter is nil (including typed nil), or when any option value is out of
|
||||
// bounds. Defaults: batch=10, maxAttempts=5, claimLease=5m, sendTimeout=10s.
|
||||
func NewDispatcher(repo ExportRepository, inserter RecordInserter, opts *DispatcherOptions) (*Dispatcher, error) {
|
||||
if isNil(repo) {
|
||||
return nil, errors.New("questiontable dispatcher: repo is nil")
|
||||
}
|
||||
if isNil(inserter) {
|
||||
return nil, errors.New("questiontable dispatcher: inserter is nil")
|
||||
}
|
||||
|
||||
batch := 10
|
||||
maxAttempts := 5
|
||||
claimLease := 5 * time.Minute
|
||||
sendTimeout := 10 * time.Second
|
||||
|
||||
if opts != nil {
|
||||
if opts.Batch < 0 {
|
||||
return nil, fmt.Errorf("questiontable dispatcher: batch must be >= 0, got %d", opts.Batch)
|
||||
}
|
||||
if opts.Batch > 0 {
|
||||
batch = opts.Batch
|
||||
}
|
||||
|
||||
if opts.MaxAttempts < 0 {
|
||||
return nil, fmt.Errorf("questiontable dispatcher: maxAttempts must be >= 0, got %d", opts.MaxAttempts)
|
||||
}
|
||||
if opts.MaxAttempts > 0 {
|
||||
maxAttempts = opts.MaxAttempts
|
||||
}
|
||||
|
||||
if opts.ClaimLease < 0 {
|
||||
return nil, fmt.Errorf("questiontable dispatcher: claimLease must be >= 0, got %v", opts.ClaimLease)
|
||||
}
|
||||
if opts.ClaimLease > 0 {
|
||||
claimLease = opts.ClaimLease
|
||||
}
|
||||
|
||||
if opts.SendTimeout < 0 {
|
||||
return nil, fmt.Errorf("questiontable dispatcher: sendTimeout must be >= 0, got %v", opts.SendTimeout)
|
||||
}
|
||||
if opts.SendTimeout > 0 {
|
||||
sendTimeout = opts.SendTimeout
|
||||
}
|
||||
}
|
||||
|
||||
return &Dispatcher{
|
||||
repo: repo,
|
||||
inserter: inserter,
|
||||
batch: batch,
|
||||
maxAttempts: maxAttempts,
|
||||
claimLease: claimLease,
|
||||
sendTimeout: sendTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RunOnce claims pending exports and dispatches them to the remote table.
|
||||
// It returns stats and any error that prevented the entire operation.
|
||||
// Individual row failures are tracked in stats.Failed and do not cause
|
||||
// RunOnce to return an error.
|
||||
func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) {
|
||||
var stats DispatcherStats
|
||||
|
||||
// Parent context precheck.
|
||||
if err := ctx.Err(); err != nil {
|
||||
return stats, fmt.Errorf("questiontable dispatcher: context invalid: %w", err)
|
||||
}
|
||||
|
||||
staleBefore := time.Now().Add(-d.claimLease)
|
||||
|
||||
items, err := d.repo.Claim(ctx, d.batch, d.maxAttempts, staleBefore)
|
||||
if err != nil {
|
||||
// Repository errors are not trusted; return stable stage-only error.
|
||||
return stats, errors.New("questiontable dispatcher: claim failed")
|
||||
}
|
||||
|
||||
stats.Claimed = len(items)
|
||||
|
||||
for _, item := range items {
|
||||
// Check parent context before each item.
|
||||
if err := ctx.Err(); err != nil {
|
||||
return stats, fmt.Errorf("questiontable dispatcher: context cancelled during dispatch: %w", err)
|
||||
}
|
||||
|
||||
sendCtx, cancel := context.WithTimeout(ctx, d.sendTimeout)
|
||||
recordID, insertErr := d.inserter.InsertRecord(sendCtx, item.Row)
|
||||
cancel()
|
||||
|
||||
if insertErr != nil {
|
||||
// Mark failed with stable code only; raw error not persisted.
|
||||
if markErr := d.repo.MarkFailed(ctx, item.ExportID, FailureCodeRemoteInsertFailed); markErr != nil {
|
||||
// Repository errors are not trusted; return stable stage-only error.
|
||||
return stats, errors.New("questiontable dispatcher: mark failed failed")
|
||||
}
|
||||
stats.Failed++
|
||||
continue
|
||||
}
|
||||
|
||||
// Mark exported with returned Notable record ID.
|
||||
if markErr := d.repo.MarkExported(ctx, item.ExportID, recordID); markErr != nil {
|
||||
// Repository errors are not trusted; return stable stage-only error.
|
||||
return stats, errors.New("questiontable dispatcher: mark exported failed")
|
||||
}
|
||||
stats.Exported++
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test doubles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// stubRepo implements ExportRepository for tests.
|
||||
type stubRepo struct {
|
||||
mu sync.Mutex
|
||||
|
||||
claimFn func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error)
|
||||
|
||||
// captured params from last Claim call.
|
||||
lastClaimLimit int
|
||||
lastClaimMaxAttempts int
|
||||
lastClaimStaleBefore time.Time
|
||||
|
||||
// exported and failed records for assertions.
|
||||
exported []exportedRecord
|
||||
failed []failedRecord
|
||||
|
||||
// markExportedErr is returned by MarkExported when non-nil.
|
||||
markExportedErr error
|
||||
// markFailedErr is returned by MarkFailed when non-nil.
|
||||
markFailedErr error
|
||||
}
|
||||
|
||||
type exportedRecord struct {
|
||||
ExportID string
|
||||
Location string
|
||||
}
|
||||
|
||||
type failedRecord struct {
|
||||
ExportID string
|
||||
FailureCode string
|
||||
}
|
||||
|
||||
func newStubRepo() *stubRepo {
|
||||
return &stubRepo{}
|
||||
}
|
||||
|
||||
func (r *stubRepo) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
r.mu.Lock()
|
||||
r.lastClaimLimit = limit
|
||||
r.lastClaimMaxAttempts = maxAttempts
|
||||
r.lastClaimStaleBefore = staleBefore
|
||||
r.mu.Unlock()
|
||||
|
||||
if r.claimFn != nil {
|
||||
return r.claimFn(ctx, limit, maxAttempts, staleBefore)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *stubRepo) MarkExported(ctx context.Context, exportID, location string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.exported = append(r.exported, exportedRecord{ExportID: exportID, Location: location})
|
||||
if r.markExportedErr != nil {
|
||||
return r.markExportedErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *stubRepo) MarkFailed(ctx context.Context, exportID, failureCode string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.failed = append(r.failed, failedRecord{ExportID: exportID, FailureCode: failureCode})
|
||||
if r.markFailedErr != nil {
|
||||
return r.markFailedErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stubInserter implements RecordInserter for tests.
|
||||
type stubInserter struct {
|
||||
mu sync.Mutex
|
||||
rows []Row
|
||||
recordID string
|
||||
err error
|
||||
blockCh chan struct{} // if set, blocks until closed
|
||||
callCount int
|
||||
|
||||
// perCallErrors maps call index (1-based) to error to return.
|
||||
// If an entry exists for a call index, that error is returned instead of a.err.
|
||||
perCallErrors map[int]error
|
||||
}
|
||||
|
||||
func newStubInserter() *stubInserter {
|
||||
return &stubInserter{recordID: "rec-test-001"}
|
||||
}
|
||||
|
||||
func (a *stubInserter) InsertRecord(ctx context.Context, row Row) (string, error) {
|
||||
a.mu.Lock()
|
||||
a.callCount++
|
||||
call := a.callCount
|
||||
a.rows = append(a.rows, row)
|
||||
blockCh := a.blockCh
|
||||
a.mu.Unlock()
|
||||
|
||||
if blockCh != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-blockCh:
|
||||
}
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
// Check per-call error override.
|
||||
if a.perCallErrors != nil {
|
||||
if e, ok := a.perCallErrors[call]; ok {
|
||||
return a.recordID, e
|
||||
}
|
||||
}
|
||||
return a.recordID, a.err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 1: empty queue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceEmptyQueue(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
if stats.Claimed != 0 {
|
||||
t.Errorf("Claimed = %d, want 0", stats.Claimed)
|
||||
}
|
||||
if stats.Exported != 0 {
|
||||
t.Errorf("Exported = %d, want 0", stats.Exported)
|
||||
}
|
||||
if stats.Failed != 0 {
|
||||
t.Errorf("Failed = %d, want 0", stats.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 2: success and location mark
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceSuccess(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.recordID = "rec-notable-abc-123"
|
||||
|
||||
exportID := "exp-001"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "hello", Answer: "world", AskerName: "alice", AskerUnionID: "union-alice"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
if stats.Claimed != 1 {
|
||||
t.Errorf("Claimed = %d, want 1", stats.Claimed)
|
||||
}
|
||||
if stats.Exported != 1 {
|
||||
t.Errorf("Exported = %d, want 1", stats.Exported)
|
||||
}
|
||||
if stats.Failed != 0 {
|
||||
t.Errorf("Failed = %d, want 0", stats.Failed)
|
||||
}
|
||||
|
||||
// Check location was marked with the Notable record ID.
|
||||
repo.mu.Lock()
|
||||
defer repo.mu.Unlock()
|
||||
if len(repo.exported) != 1 {
|
||||
t.Fatalf("exported records = %d, want 1", len(repo.exported))
|
||||
}
|
||||
if repo.exported[0].ExportID != exportID {
|
||||
t.Errorf("exported exportID = %q, want %q", repo.exported[0].ExportID, exportID)
|
||||
}
|
||||
if repo.exported[0].Location != "rec-notable-abc-123" {
|
||||
t.Errorf("exported Location = %q, want %q", repo.exported[0].Location, "rec-notable-abc-123")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 3: insert error => stable failure code, raw error absent
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceInsertErrorStableCode(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
// Use an error that contains "secrets" that must not leak.
|
||||
inserter.err = fmt.Errorf("network: connect to https://api.dingtalk.com?operatorId=secret-operator failed: row contains secret-data-xyz")
|
||||
|
||||
exportID := "exp-002"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
if stats.Claimed != 1 {
|
||||
t.Errorf("Claimed = %d, want 1", stats.Claimed)
|
||||
}
|
||||
if stats.Exported != 0 {
|
||||
t.Errorf("Exported = %d, want 0", stats.Exported)
|
||||
}
|
||||
if stats.Failed != 1 {
|
||||
t.Errorf("Failed = %d, want 1", stats.Failed)
|
||||
}
|
||||
|
||||
// Check failure code is stable, not raw error.
|
||||
repo.mu.Lock()
|
||||
defer repo.mu.Unlock()
|
||||
if len(repo.failed) != 1 {
|
||||
t.Fatalf("failed records = %d, want 1", len(repo.failed))
|
||||
}
|
||||
if repo.failed[0].ExportID != exportID {
|
||||
t.Errorf("failed exportID = %q, want %q", repo.failed[0].ExportID, exportID)
|
||||
}
|
||||
if repo.failed[0].FailureCode != FailureCodeRemoteInsertFailed {
|
||||
t.Errorf("failure code = %q, want %q", repo.failed[0].FailureCode, FailureCodeRemoteInsertFailed)
|
||||
}
|
||||
|
||||
// The raw error with secrets must not appear in stats or returned values.
|
||||
// (Already verified: stats don't leak error strings.)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 4: blocking inserter respects per-item timeout
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOncePerItemTimeout(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.blockCh = make(chan struct{}) // never unblocks
|
||||
|
||||
exportID := "exp-timeout"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
opts := &DispatcherOptions{SendTimeout: 50 * time.Millisecond}
|
||||
d, err := NewDispatcher(repo, inserter, opts)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
stats, err := d.RunOnce(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
|
||||
if stats.Failed != 1 {
|
||||
t.Errorf("Failed = %d, want 1 (timeout should cause mark failed)", stats.Failed)
|
||||
}
|
||||
if stats.Exported != 0 {
|
||||
t.Errorf("Exported = %d, want 0", stats.Exported)
|
||||
}
|
||||
|
||||
// Verify failure code is stable.
|
||||
repo.mu.Lock()
|
||||
defer repo.mu.Unlock()
|
||||
if len(repo.failed) != 1 {
|
||||
t.Fatalf("failed records = %d, want 1", len(repo.failed))
|
||||
}
|
||||
if repo.failed[0].FailureCode != FailureCodeRemoteInsertFailed {
|
||||
t.Errorf("failure code = %q, want %q", repo.failed[0].FailureCode, FailureCodeRemoteInsertFailed)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 5: claim receives batch/max/stale time near expected
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceClaimParams(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
opts := &DispatcherOptions{
|
||||
Batch: 7,
|
||||
MaxAttempts: 3,
|
||||
ClaimLease: 2 * time.Minute,
|
||||
SendTimeout: 5 * time.Second,
|
||||
}
|
||||
d, err := NewDispatcher(repo, inserter, opts)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
before := time.Now()
|
||||
_, err = d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
after := time.Now()
|
||||
|
||||
repo.mu.Lock()
|
||||
limit := repo.lastClaimLimit
|
||||
maxAtt := repo.lastClaimMaxAttempts
|
||||
staleBefore := repo.lastClaimStaleBefore
|
||||
repo.mu.Unlock()
|
||||
|
||||
if limit != 7 {
|
||||
t.Errorf("claim limit = %d, want 7", limit)
|
||||
}
|
||||
if maxAtt != 3 {
|
||||
t.Errorf("claim maxAttempts = %d, want 3", maxAtt)
|
||||
}
|
||||
|
||||
// staleBefore should be approximately now - 2m.
|
||||
expectedStale := before.Add(-2 * time.Minute)
|
||||
// Allow some tolerance.
|
||||
if staleBefore.Before(expectedStale.Add(-2*time.Second)) || staleBefore.After(after.Add(-2*time.Minute).Add(2*time.Second)) {
|
||||
t.Errorf("staleBefore = %v, expected near %v (before=%v, after=%v)", staleBefore, expectedStale, before, after)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 6: parent cancellation before claim and between items
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceParentCancelledBeforeClaim(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
_, err = d.RunOnce(ctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for cancelled context")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "context invalid") {
|
||||
t.Errorf("error = %v, want 'context invalid'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherRunOnceParentCancelledBetweenItems(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.recordID = "rec-1"
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: "exp-1", Row: Row{Question: "q1", Answer: "a1", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
{ExportID: "exp-2", Row: Row{Question: "q2", Answer: "a2", AskerName: "y", AskerUnionID: "union-y"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Wrap inserter to cancel parent context after the first InsertRecord call.
|
||||
cancellingInserter := &cancellingInserter{
|
||||
inner: inserter,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, cancellingInserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(ctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for cancelled context between items")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "context cancelled during dispatch") {
|
||||
t.Errorf("error = %v, want 'context cancelled during dispatch'", err)
|
||||
}
|
||||
// First item should have been exported before cancellation.
|
||||
if stats.Exported != 1 {
|
||||
t.Errorf("Exported = %d, want 1", stats.Exported)
|
||||
}
|
||||
}
|
||||
|
||||
// cancellingInserter wraps a RecordInserter and cancels a context after the first call.
|
||||
type cancellingInserter struct {
|
||||
inner RecordInserter
|
||||
cancel context.CancelFunc
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
}
|
||||
|
||||
func (a *cancellingInserter) InsertRecord(ctx context.Context, row Row) (string, error) {
|
||||
a.mu.Lock()
|
||||
a.calls++
|
||||
calls := a.calls
|
||||
a.mu.Unlock()
|
||||
|
||||
result, err := a.inner.InsertRecord(ctx, row)
|
||||
|
||||
if calls == 1 {
|
||||
a.cancel()
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 7: claim/mark errors and stats semantics
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceClaimError(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
claimErr := errors.New("database connection refused")
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return nil, claimErr
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for claim failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "claim failed") {
|
||||
t.Errorf("error = %v, want 'claim failed' stage wrapper", err)
|
||||
}
|
||||
if stats.Claimed != 0 {
|
||||
t.Errorf("Claimed = %d, want 0 on claim error", stats.Claimed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherRunOnceMarkExportedError(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.recordID = "rec-mark-err"
|
||||
|
||||
repo.markExportedErr = errors.New("mark exported db error")
|
||||
|
||||
exportID := "exp-mark-err"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mark exported failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "mark exported failed") {
|
||||
t.Errorf("error = %v, want 'mark exported failed' stage wrapper", err)
|
||||
}
|
||||
// Stats should reflect the insert succeeded before mark failed.
|
||||
if stats.Exported != 0 {
|
||||
t.Errorf("Exported = %d, want 0 (mark failed before increment)", stats.Exported)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherRunOnceStatsSemantics(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.recordID = "rec-ok"
|
||||
|
||||
// 2 success, 1 failure.
|
||||
inserter.perCallErrors = map[int]error{
|
||||
2: errors.New("network error"),
|
||||
}
|
||||
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: "exp-ok1", Row: Row{Question: "q1", Answer: "a1", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
{ExportID: "exp-fail", Row: Row{Question: "q2", Answer: "a2", AskerName: "y", AskerUnionID: "union-y"}, Attempts: 0},
|
||||
{ExportID: "exp-ok2", Row: Row{Question: "q3", Answer: "a3", AskerName: "z", AskerUnionID: "union-z"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
if stats.Claimed != 3 {
|
||||
t.Errorf("Claimed = %d, want 3", stats.Claimed)
|
||||
}
|
||||
if stats.Exported != 2 {
|
||||
t.Errorf("Exported = %d, want 2", stats.Exported)
|
||||
}
|
||||
if stats.Failed != 1 {
|
||||
t.Errorf("Failed = %d, want 1", stats.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 8: constructor invalid bounds, nil, typed-nil
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestNewDispatcherNilDeps(t *testing.T) {
|
||||
inserter := newStubInserter()
|
||||
|
||||
_, err := NewDispatcher(nil, inserter, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil repo")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "repo is nil") {
|
||||
t.Errorf("error = %v, want 'repo is nil'", err)
|
||||
}
|
||||
|
||||
repo := newStubRepo()
|
||||
_, err = NewDispatcher(repo, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil inserter")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "inserter is nil") {
|
||||
t.Errorf("error = %v, want 'inserter is nil'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDispatcherTypedNil(t *testing.T) {
|
||||
// Typed nil: interface value is non-nil but underlying concrete is nil.
|
||||
var typedNilRepo *stubRepo = nil
|
||||
var repo ExportRepository = typedNilRepo
|
||||
|
||||
inserter := newStubInserter()
|
||||
_, err := NewDispatcher(repo, inserter, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for typed-nil repo")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "repo is nil") {
|
||||
t.Errorf("error = %v, want 'repo is nil'", err)
|
||||
}
|
||||
|
||||
repo2 := newStubRepo()
|
||||
var typedNilInserter *stubInserter = nil
|
||||
var inserter2 RecordInserter = typedNilInserter
|
||||
|
||||
_, err = NewDispatcher(repo2, inserter2, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for typed-nil inserter")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "inserter is nil") {
|
||||
t.Errorf("error = %v, want 'inserter is nil'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDispatcherInvalidBounds(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
opts DispatcherOptions
|
||||
want string
|
||||
}{
|
||||
{"negative batch", DispatcherOptions{Batch: -1}, "batch must be >= 0"},
|
||||
{"negative maxAttempts", DispatcherOptions{MaxAttempts: -1}, "maxAttempts must be >= 0"},
|
||||
{"negative claimLease", DispatcherOptions{ClaimLease: -1 * time.Second}, "claimLease must be >= 0"},
|
||||
{"negative sendTimeout", DispatcherOptions{SendTimeout: -1 * time.Second}, "sendTimeout must be >= 0"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, err := NewDispatcher(repo, inserter, &tt.opts)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("error = %v, want containing %q", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDispatcherDefaults(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
if d.batch != 10 {
|
||||
t.Errorf("batch = %d, want 10", d.batch)
|
||||
}
|
||||
if d.maxAttempts != 5 {
|
||||
t.Errorf("maxAttempts = %d, want 5", d.maxAttempts)
|
||||
}
|
||||
if d.claimLease != 5*time.Minute {
|
||||
t.Errorf("claimLease = %v, want 5m", d.claimLease)
|
||||
}
|
||||
if d.sendTimeout != 10*time.Second {
|
||||
t.Errorf("sendTimeout = %v, want 10s", d.sendTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDispatcherZeroBatch(t *testing.T) {
|
||||
// Zero batch is allowed (validates as >= 0, but not > 0 so use default).
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
opts := &DispatcherOptions{Batch: 0}
|
||||
d, err := NewDispatcher(repo, inserter, opts)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher with batch=0: %v", err)
|
||||
}
|
||||
if d.batch != 10 {
|
||||
t.Errorf("batch = %d, want 10 (default when opts.Batch=0)", d.batch)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 9: exact Row passed to inserter
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceExactRowPassed(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
row := Row{
|
||||
Question: "怎么修?",
|
||||
Answer: "按步骤操作",
|
||||
AskedTime: time.Date(2025, 6, 15, 14, 30, 0, 0, time.FixedZone("CST", 8*60*60)),
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "union-zhang-san",
|
||||
TriggerPerson: "李四",
|
||||
Department: "研发部",
|
||||
Region: "华东",
|
||||
}
|
||||
|
||||
exportID := "exp-cells"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: row, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
_, err = d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
|
||||
inserter.mu.Lock()
|
||||
defer inserter.mu.Unlock()
|
||||
if len(inserter.rows) != 1 {
|
||||
t.Fatalf("inserter received %d rows, want 1", len(inserter.rows))
|
||||
}
|
||||
|
||||
got := inserter.rows[0]
|
||||
|
||||
if got.Question != row.Question {
|
||||
t.Errorf("Question = %q, want %q", got.Question, row.Question)
|
||||
}
|
||||
if got.Answer != row.Answer {
|
||||
t.Errorf("Answer = %q, want %q", got.Answer, row.Answer)
|
||||
}
|
||||
if !got.AskedTime.Equal(row.AskedTime) {
|
||||
t.Errorf("AskedTime = %v, want %v", got.AskedTime, row.AskedTime)
|
||||
}
|
||||
if got.AskerName != row.AskerName {
|
||||
t.Errorf("AskerName = %q, want %q", got.AskerName, row.AskerName)
|
||||
}
|
||||
if got.AskerUnionID != row.AskerUnionID {
|
||||
t.Errorf("AskerUnionID = %q, want %q", got.AskerUnionID, row.AskerUnionID)
|
||||
}
|
||||
if got.TriggerPerson != row.TriggerPerson {
|
||||
t.Errorf("TriggerPerson = %q, want %q", got.TriggerPerson, row.TriggerPerson)
|
||||
}
|
||||
if got.Department != row.Department {
|
||||
t.Errorf("Department = %q, want %q", got.Department, row.Department)
|
||||
}
|
||||
if got.Region != row.Region {
|
||||
t.Errorf("Region = %q, want %q", got.Region, row.Region)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Additional: RunOnce returns error when sendCtx expires but parent OK
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceSendTimeoutDoesNotKillParent(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.blockCh = make(chan struct{}) // never unblocks
|
||||
|
||||
exportID := "exp-timeout2"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
opts := &DispatcherOptions{SendTimeout: 20 * time.Millisecond}
|
||||
d, err := NewDispatcher(repo, inserter, opts)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
stats, err := d.RunOnce(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("RunOnce should not fail on per-item timeout: %v", err)
|
||||
}
|
||||
if stats.Failed != 1 {
|
||||
t.Errorf("Failed = %d, want 1", stats.Failed)
|
||||
}
|
||||
|
||||
// Parent context should still be alive.
|
||||
if ctx.Err() != nil {
|
||||
t.Errorf("parent context should still be alive, got %v", ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Additional: RecordInserter interface satisfaction check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestClientSatisfiesRecordInserter(t *testing.T) {
|
||||
// Compile-time check: *Client implements RecordInserter.
|
||||
var _ RecordInserter = (*Client)(nil)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error leakage: repository errors must not leak secrets
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDispatcherRunOnceClaimErrorNoLeak(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
|
||||
// Claim error containing SQL/turn/export/person secrets.
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return nil, fmt.Errorf("SQLSTATE 42P01: relation \"turn_export_person\" does not exist")
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
_, err = d.RunOnce(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for claim failure")
|
||||
}
|
||||
|
||||
errStr := err.Error()
|
||||
secrets := []string{"SQLSTATE", "42P01", "turn_export_person", "relation"}
|
||||
for _, s := range secrets {
|
||||
if strings.Contains(errStr, s) {
|
||||
t.Errorf("error leaks secret %q: %v", s, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherRunOnceMarkFailedNoLeak(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.err = errors.New("some insert error")
|
||||
|
||||
repo.markFailedErr = fmt.Errorf("SQLSTATE 23505: duplicate key in export_person_report")
|
||||
|
||||
exportID := "exp-leak-mf"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
_, err = d.RunOnce(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mark failed failure")
|
||||
}
|
||||
|
||||
errStr := err.Error()
|
||||
secrets := []string{"SQLSTATE", "23505", "export_person_report", "duplicate"}
|
||||
for _, s := range secrets {
|
||||
if strings.Contains(errStr, s) {
|
||||
t.Errorf("error leaks secret %q: %v", s, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherRunOnceMarkExportedNoLeak(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
inserter := newStubInserter()
|
||||
inserter.recordID = "rec-leak"
|
||||
|
||||
repo.markExportedErr = fmt.Errorf("SQLSTATE 08006: connection lost for turn_export_write")
|
||||
|
||||
exportID := "exp-leak-me"
|
||||
repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return []PendingExport{
|
||||
{ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher: %v", err)
|
||||
}
|
||||
|
||||
_, err = d.RunOnce(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mark exported failure")
|
||||
}
|
||||
|
||||
errStr := err.Error()
|
||||
secrets := []string{"SQLSTATE", "08006", "turn_export_write", "connection"}
|
||||
for _, s := range secrets {
|
||||
if strings.Contains(errStr, s) {
|
||||
t.Errorf("error leaks secret %q: %v", s, errStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Value-type constructor: non-pointer implementations should not panic
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// valueRepo is a non-pointer ExportRepository implementation.
|
||||
type valueRepo struct{}
|
||||
|
||||
func (v valueRepo) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (v valueRepo) MarkExported(ctx context.Context, exportID, location string) error { return nil }
|
||||
func (v valueRepo) MarkFailed(ctx context.Context, exportID, failureCode string) error { return nil }
|
||||
|
||||
// valueInserter is a non-pointer RecordInserter implementation.
|
||||
type valueInserter struct{}
|
||||
|
||||
func (v valueInserter) InsertRecord(ctx context.Context, row Row) (string, error) {
|
||||
return "rec-value-001", nil
|
||||
}
|
||||
|
||||
func TestNewDispatcherValueTypeRepo(t *testing.T) {
|
||||
// value-type repo should not panic (was: reflect.ValueOf(x).IsNil() on non-nilable kind).
|
||||
var repo ExportRepository = valueRepo{}
|
||||
inserter := newStubInserter()
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher with value-type repo: %v", err)
|
||||
}
|
||||
_ = d
|
||||
}
|
||||
|
||||
func TestNewDispatcherValueTypeInserter(t *testing.T) {
|
||||
repo := newStubRepo()
|
||||
var inserter RecordInserter = valueInserter{}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher with value-type inserter: %v", err)
|
||||
}
|
||||
_ = d
|
||||
}
|
||||
|
||||
func TestNewDispatcherValueTypeBoth(t *testing.T) {
|
||||
var repo ExportRepository = valueRepo{}
|
||||
var inserter RecordInserter = valueInserter{}
|
||||
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDispatcher with value-type both: %v", err)
|
||||
}
|
||||
_ = d
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Field IDs for the DingTalk Notable v1 question table.
|
||||
// Verified against the live Notable v1 base.
|
||||
const (
|
||||
FieldChineseQuestion = "ZaMZF6j" // text
|
||||
FieldAskedTime = "SCug9My" // date (Unix milliseconds)
|
||||
FieldAsker = "S2XA1uZ" // user (array of {name, unionId})
|
||||
FieldOriginalQuestion = "bETcL3r" // text
|
||||
FieldAnswer = "Y4cpmxU" // text
|
||||
FieldTriggerPerson = "JgY2f1z" // text
|
||||
FieldLanguage = "DNIV3mQ" // text
|
||||
FieldDepartment = "eBc6a6b" // text
|
||||
FieldRegion = "fPNLeVW" // text
|
||||
)
|
||||
|
||||
// Row holds the data needed to produce a Notable v1 typed record.
|
||||
type Row struct {
|
||||
Question string
|
||||
Answer string
|
||||
AskedTime time.Time
|
||||
AskerName string
|
||||
AskerUnionID string
|
||||
TriggerPerson string
|
||||
Department string
|
||||
Region string
|
||||
}
|
||||
|
||||
// ToFields returns a typed field-ID → value map suitable for the Notable v1
|
||||
// InsertRecord request body. The caller is responsible for the semantics of
|
||||
// each field; this method only handles mapping, language detection, time
|
||||
// formatting, and formula-injection sanitisation.
|
||||
// The five v1 select fields (QMn9UoU, H3gtTuv, nFvv8OR, UMqUPAG, lnF7gF9)
|
||||
// are omitted entirely.
|
||||
func (r Row) ToFields() map[string]interface{} {
|
||||
fields := make(map[string]interface{})
|
||||
|
||||
lang := detectLanguage(r.Question)
|
||||
|
||||
// ChineseQuestion: only when Han present.
|
||||
if lang == "中文" {
|
||||
fields[FieldChineseQuestion] = sanitise(r.Question)
|
||||
}
|
||||
|
||||
// Answer.
|
||||
fields[FieldAnswer] = sanitise(r.Answer)
|
||||
|
||||
// AskedTime: Unix milliseconds if non-zero; omit if zero.
|
||||
if !r.AskedTime.IsZero() {
|
||||
fields[FieldAskedTime] = r.AskedTime.UnixMilli()
|
||||
}
|
||||
|
||||
// Asker: user object only when AskerUnionID is non-blank.
|
||||
if strings.TrimSpace(r.AskerUnionID) != "" {
|
||||
fields[FieldAsker] = []interface{}{
|
||||
map[string]interface{}{
|
||||
"name": strings.TrimSpace(r.AskerName),
|
||||
"unionId": strings.TrimSpace(r.AskerUnionID),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// OriginalQuestion.
|
||||
fields[FieldOriginalQuestion] = sanitise(r.Question)
|
||||
|
||||
// Language.
|
||||
fields[FieldLanguage] = sanitise(lang)
|
||||
|
||||
// TriggerPerson: fallback to AskerName.
|
||||
triggerPerson := r.TriggerPerson
|
||||
if triggerPerson == "" {
|
||||
triggerPerson = r.AskerName
|
||||
}
|
||||
fields[FieldTriggerPerson] = sanitise(triggerPerson)
|
||||
|
||||
// Department.
|
||||
fields[FieldDepartment] = sanitise(r.Department)
|
||||
|
||||
// Region.
|
||||
fields[FieldRegion] = sanitise(r.Region)
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
// detectLanguage returns "中文" when s contains any Han character,
|
||||
// "英文" when it contains Latin letters but no Han,
|
||||
// and "其他" otherwise.
|
||||
func detectLanguage(s string) string {
|
||||
hasHan := false
|
||||
hasLatin := false
|
||||
for _, r := range s {
|
||||
if isHan(r) {
|
||||
hasHan = true
|
||||
}
|
||||
if isLatin(r) {
|
||||
hasLatin = true
|
||||
}
|
||||
}
|
||||
if hasHan {
|
||||
return "中文"
|
||||
}
|
||||
if hasLatin {
|
||||
return "英文"
|
||||
}
|
||||
return "其他"
|
||||
}
|
||||
|
||||
func isHan(r rune) bool {
|
||||
return unicode.Is(unicode.Han, r)
|
||||
}
|
||||
|
||||
func isLatin(r rune) bool {
|
||||
return unicode.Is(unicode.Latin, r)
|
||||
}
|
||||
|
||||
// sanitise protects against spreadsheet formula injection. If the string
|
||||
// begins with =, +, -, or @, a single apostrophe is prefixed. The string
|
||||
// is otherwise returned unchanged.
|
||||
func sanitise(s string) string {
|
||||
if s == "" {
|
||||
return s
|
||||
}
|
||||
r, _ := utf8.DecodeRuneInString(s)
|
||||
switch r {
|
||||
case '=', '+', '-', '@':
|
||||
return "'" + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRowToFieldsExactMapping(t *testing.T) {
|
||||
shanghai, _ := time.LoadLocation("Asia/Shanghai")
|
||||
asked := time.Date(2025, 6, 15, 14, 30, 0, 0, shanghai)
|
||||
|
||||
r := Row{
|
||||
Question: "这个怎么修?",
|
||||
Answer: "请按以下步骤操作。",
|
||||
AskedTime: asked,
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "union-zhang-san",
|
||||
TriggerPerson: "李四",
|
||||
Department: "研发部",
|
||||
Region: "华东",
|
||||
}
|
||||
|
||||
fields := r.ToFields()
|
||||
|
||||
// ChineseQuestion (only when Han present).
|
||||
if fields[FieldChineseQuestion] != "这个怎么修?" {
|
||||
t.Errorf("ChineseQuestion = %q, want %q", fields[FieldChineseQuestion], "这个怎么修?")
|
||||
}
|
||||
|
||||
// Answer.
|
||||
if fields[FieldAnswer] != "请按以下步骤操作。" {
|
||||
t.Errorf("Answer = %q, want %q", fields[FieldAnswer], "请按以下步骤操作。")
|
||||
}
|
||||
|
||||
// AskedTime: Unix milliseconds.
|
||||
expectedMS := asked.UnixMilli()
|
||||
if fields[FieldAskedTime] != expectedMS {
|
||||
t.Errorf("AskedTime = %v (%T), want %v (int64)", fields[FieldAskedTime], fields[FieldAskedTime], expectedMS)
|
||||
}
|
||||
|
||||
// Asker: user array.
|
||||
userArr, ok := fields[FieldAsker].([]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Asker not a []interface{}, got %T", fields[FieldAsker])
|
||||
}
|
||||
if len(userArr) != 1 {
|
||||
t.Fatalf("Asker len = %d, want 1", len(userArr))
|
||||
}
|
||||
userObj, ok := userArr[0].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Asker[0] not a map[string]interface{}, got %T", userArr[0])
|
||||
}
|
||||
if userObj["name"] != "张三" {
|
||||
t.Errorf("Asker name = %q, want %q", userObj["name"], "张三")
|
||||
}
|
||||
if userObj["unionId"] != "union-zhang-san" {
|
||||
t.Errorf("Asker unionId = %q, want %q", userObj["unionId"], "union-zhang-san")
|
||||
}
|
||||
|
||||
// OriginalQuestion.
|
||||
if fields[FieldOriginalQuestion] != "这个怎么修?" {
|
||||
t.Errorf("OriginalQuestion = %q, want %q", fields[FieldOriginalQuestion], "这个怎么修?")
|
||||
}
|
||||
|
||||
// Language.
|
||||
if fields[FieldLanguage] != "中文" {
|
||||
t.Errorf("Language = %q, want %q", fields[FieldLanguage], "中文")
|
||||
}
|
||||
|
||||
// TriggerPerson.
|
||||
if fields[FieldTriggerPerson] != "李四" {
|
||||
t.Errorf("TriggerPerson = %q, want %q", fields[FieldTriggerPerson], "李四")
|
||||
}
|
||||
|
||||
// Department.
|
||||
if fields[FieldDepartment] != "研发部" {
|
||||
t.Errorf("Department = %q, want %q", fields[FieldDepartment], "研发部")
|
||||
}
|
||||
|
||||
// Region.
|
||||
if fields[FieldRegion] != "华东" {
|
||||
t.Errorf("Region = %q, want %q", fields[FieldRegion], "华东")
|
||||
}
|
||||
|
||||
// Omitted: the five select fields must not be present.
|
||||
omitted := []string{"QMn9UoU", "H3gtTuv", "nFvv8OR", "UMqUPAG", "lnF7gF9"}
|
||||
for _, fid := range omitted {
|
||||
if _, exists := fields[fid]; exists {
|
||||
t.Errorf("select field %q should be omitted but is present", fid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsDateZeroOmission(t *testing.T) {
|
||||
r := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: "user",
|
||||
AskerUnionID: "union-1",
|
||||
// AskedTime is zero.
|
||||
}
|
||||
fields := r.ToFields()
|
||||
if _, exists := fields[FieldAskedTime]; exists {
|
||||
t.Error("AskedTime field should be omitted when zero")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsDateInt64UnixMilli(t *testing.T) {
|
||||
shanghai, _ := time.LoadLocation("Asia/Shanghai")
|
||||
asked := time.Date(2026, 1, 2, 3, 4, 5, 0, shanghai)
|
||||
|
||||
r := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskedTime: asked,
|
||||
AskerName: "user",
|
||||
AskerUnionID: "union-1",
|
||||
}
|
||||
fields := r.ToFields()
|
||||
got, ok := fields[FieldAskedTime].(int64)
|
||||
if !ok {
|
||||
t.Fatalf("AskedTime is %T, want int64", fields[FieldAskedTime])
|
||||
}
|
||||
if got != asked.UnixMilli() {
|
||||
t.Errorf("AskedTime = %d, want %d", got, asked.UnixMilli())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsUserShape(t *testing.T) {
|
||||
// With union ID: user array present.
|
||||
r := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: " 张三 ",
|
||||
AskerUnionID: " union-123 ",
|
||||
}
|
||||
fields := r.ToFields()
|
||||
userArr, ok := fields[FieldAsker].([]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Asker not present or wrong type: %T", fields[FieldAsker])
|
||||
}
|
||||
userObj := userArr[0].(map[string]interface{})
|
||||
if userObj["name"] != "张三" {
|
||||
t.Errorf("name = %q, want %q (trimmed)", userObj["name"], "张三")
|
||||
}
|
||||
if userObj["unionId"] != "union-123" {
|
||||
t.Errorf("unionId = %q, want %q (trimmed)", userObj["unionId"], "union-123")
|
||||
}
|
||||
|
||||
// Without union ID: Asker field omitted.
|
||||
r2 := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "",
|
||||
}
|
||||
fields2 := r2.ToFields()
|
||||
if _, exists := fields2[FieldAsker]; exists {
|
||||
t.Error("Asker field should be omitted when union ID is blank")
|
||||
}
|
||||
|
||||
// Whitespace-only union ID: omitted.
|
||||
r3 := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: "张三",
|
||||
AskerUnionID: " ",
|
||||
}
|
||||
fields3 := r3.ToFields()
|
||||
if _, exists := fields3[FieldAsker]; exists {
|
||||
t.Error("Asker field should be omitted when union ID is whitespace-only")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsChineseQuestionPolicy(t *testing.T) {
|
||||
// English question: ChineseQuestion omitted.
|
||||
r := Row{
|
||||
Question: "How to fix this?",
|
||||
Answer: "Follow these steps.",
|
||||
AskerName: "Alice",
|
||||
AskerUnionID: "union-alice",
|
||||
}
|
||||
fields := r.ToFields()
|
||||
if _, exists := fields[FieldChineseQuestion]; exists {
|
||||
t.Error("ChineseQuestion should be omitted for English question")
|
||||
}
|
||||
if fields[FieldLanguage] != "英文" {
|
||||
t.Errorf("Language = %q, want 英文", fields[FieldLanguage])
|
||||
}
|
||||
|
||||
// Chinese question: ChineseQuestion contains the question.
|
||||
r2 := Row{
|
||||
Question: "怎么解决?",
|
||||
Answer: "按步骤操作。",
|
||||
AskerName: "Bob",
|
||||
AskerUnionID: "union-bob",
|
||||
}
|
||||
fields2 := r2.ToFields()
|
||||
if fields2[FieldChineseQuestion] != "怎么解决?" {
|
||||
t.Errorf("ChineseQuestion = %q, want %q", fields2[FieldChineseQuestion], "怎么解决?")
|
||||
}
|
||||
if fields2[FieldLanguage] != "中文" {
|
||||
t.Errorf("Language = %q, want 中文", fields2[FieldLanguage])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectLanguage(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{"你好", "中文"},
|
||||
{"Hello", "英文"},
|
||||
{"Hello世界", "中文"}, // Han takes priority
|
||||
{"12345", "其他"},
|
||||
{"", "其他"},
|
||||
{"こんにちは", "其他"}, // Japanese kana
|
||||
{"Привет", "其他"}, // Cyrillic
|
||||
{"Español", "英文"}, // accented Latin via unicode.Latin
|
||||
{"café", "英文"}, // accented Latin
|
||||
{"Déjà vu", "英文"}, // accented Latin
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := detectLanguage(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("detectLanguage(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitiseFormulaInjection(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{"=SUM(A1:A10)", "'=SUM(A1:A10)"},
|
||||
{"+A1", "'+A1"},
|
||||
{"-A1", "'-A1"},
|
||||
{"@SUM", "'@SUM"},
|
||||
{"normal text", "normal text"},
|
||||
{"=", "'="}, // = is the first rune, prefixed to '='
|
||||
{"", ""},
|
||||
{" leading space", " leading space"},
|
||||
{"1=2", "1=2"}, // doesn't start with a formula char
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := sanitise(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("sanitise(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitiseDoesNotMutateNonFormula(t *testing.T) {
|
||||
inputs := []string{"hello", "世界", "123", "=SUM(", " a", "a=", "null"}
|
||||
for _, in := range inputs {
|
||||
got := sanitise(in)
|
||||
// Only "=SUM(" should be prefixed.
|
||||
switch in {
|
||||
case "=SUM(":
|
||||
if got != "'=SUM(" {
|
||||
t.Errorf("sanitise(%q) = %q, want '=SUM(", in, got)
|
||||
}
|
||||
default:
|
||||
if got != in {
|
||||
t.Errorf("sanitise(%q) = %q, want %q (no change)", in, got, in)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTriggerPersonFallback(t *testing.T) {
|
||||
// When TriggerPerson is empty, fall back to AskerName.
|
||||
r := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "union-1",
|
||||
TriggerPerson: "",
|
||||
}
|
||||
fields := r.ToFields()
|
||||
if fields[FieldTriggerPerson] != "张三" {
|
||||
t.Errorf("TriggerPerson = %q, want %q (fallback to asker)", fields[FieldTriggerPerson], "张三")
|
||||
}
|
||||
|
||||
// When TriggerPerson is set, use it.
|
||||
r2 := Row{
|
||||
Question: "test",
|
||||
Answer: "answer",
|
||||
AskerName: "张三",
|
||||
AskerUnionID: "union-1",
|
||||
TriggerPerson: "nickname",
|
||||
}
|
||||
fields2 := r2.ToFields()
|
||||
if fields2[FieldTriggerPerson] != "nickname" {
|
||||
t.Errorf("TriggerPerson = %q, want %q (use trigger)", fields2[FieldTriggerPerson], "nickname")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormulaInjectionOnAllColumns(t *testing.T) {
|
||||
shanghai, _ := time.LoadLocation("Asia/Shanghai")
|
||||
asked := time.Date(2025, 1, 1, 0, 0, 0, 0, shanghai)
|
||||
|
||||
// Use a question that starts with formula char AND contains Han so
|
||||
// the Chinese-question field is populated.
|
||||
r := Row{
|
||||
Question: "=修复()",
|
||||
Answer: "+cmd",
|
||||
AskedTime: asked,
|
||||
AskerName: "-张三",
|
||||
AskerUnionID: "union-sanitise",
|
||||
TriggerPerson: "@trigger",
|
||||
Department: "=DEPT",
|
||||
Region: "normal",
|
||||
}
|
||||
fields := r.ToFields()
|
||||
|
||||
// Chinese question: "=修复()" has Han, so it's Chinese and gets sanitised.
|
||||
if fields[FieldChineseQuestion] != "'=修复()" {
|
||||
t.Errorf("ChineseQuestion = %q, want %q", fields[FieldChineseQuestion], "'=修复()")
|
||||
}
|
||||
// Answer: "+cmd" → "'+cmd"
|
||||
if fields[FieldAnswer] != "'+cmd" {
|
||||
t.Errorf("Answer = %q, want %q", fields[FieldAnswer], "'+cmd")
|
||||
}
|
||||
// OriginalQuestion: "=修复()" → "'=修复()"
|
||||
if fields[FieldOriginalQuestion] != "'=修复()" {
|
||||
t.Errorf("OriginalQuestion = %q, want %q", fields[FieldOriginalQuestion], "'=修复()")
|
||||
}
|
||||
// TriggerPerson: "@trigger" → "'@trigger"
|
||||
if fields[FieldTriggerPerson] != "'@trigger" {
|
||||
t.Errorf("TriggerPerson = %q, want %q", fields[FieldTriggerPerson], "'@trigger")
|
||||
}
|
||||
// Department: "=DEPT" → "'=DEPT"
|
||||
if fields[FieldDepartment] != "'=DEPT" {
|
||||
t.Errorf("Department = %q, want %q", fields[FieldDepartment], "'=DEPT")
|
||||
}
|
||||
// Region: "normal" → no change
|
||||
if fields[FieldRegion] != "normal" {
|
||||
t.Errorf("Region = %q, want %q", fields[FieldRegion], "normal")
|
||||
}
|
||||
// Asker name: "-张三" → "'-张三" (via user object)
|
||||
userArr := fields[FieldAsker].([]interface{})
|
||||
userObj := userArr[0].(map[string]interface{})
|
||||
// Asker name is NOT sanitised per the contract (only text fields are sanitised),
|
||||
// but the name is trimmed. Let's verify — the task says trim only union ID/name,
|
||||
// preserve question/answer text. So name is sanitised via TrimSpace, not sanitise().
|
||||
// Actually, sanitise is only applied to the text fields. Asker name goes through
|
||||
// strings.TrimSpace but not sanitise. Let's check the behavior.
|
||||
// The task says: "Trim only union ID/name for the user object if existing
|
||||
// conventions require; preserve question/answer text." So name is trimmed, not
|
||||
// sanitised. We should verify the trimmed name.
|
||||
if userObj["name"] != "-张三" {
|
||||
t.Errorf("Asker name = %q, want %q", userObj["name"], "-张三")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user