feat: add FAQ uncovered workflow
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
package faqtable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const FailureCodeRemoteInsertFailed = "remote_faq_table_insert_failed"
|
||||
|
||||
type PendingExport struct {
|
||||
CaseID string
|
||||
Row Row
|
||||
Attempts int
|
||||
}
|
||||
|
||||
type ExportRepository interface {
|
||||
Claim(context.Context, int, int, time.Time) ([]PendingExport, error)
|
||||
MarkExported(context.Context, string, string) error
|
||||
MarkFailed(context.Context, string, string) error
|
||||
}
|
||||
|
||||
type FieldsInserter interface {
|
||||
InsertFields(context.Context, map[string]interface{}) (string, error)
|
||||
}
|
||||
|
||||
type DispatcherOptions struct {
|
||||
Batch int
|
||||
MaxAttempts int
|
||||
ClaimLease time.Duration
|
||||
SendTimeout time.Duration
|
||||
}
|
||||
|
||||
type DispatcherStats struct {
|
||||
Claimed int
|
||||
Exported int
|
||||
Failed int
|
||||
}
|
||||
|
||||
type Dispatcher struct {
|
||||
repo ExportRepository
|
||||
inserter FieldsInserter
|
||||
batch int
|
||||
maxAttempts int
|
||||
claimLease time.Duration
|
||||
sendTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewDispatcher(repo ExportRepository, inserter FieldsInserter, opts *DispatcherOptions) (*Dispatcher, error) {
|
||||
if isNil(repo) || isNil(inserter) {
|
||||
return nil, errors.New("faqtable dispatcher dependencies are required")
|
||||
}
|
||||
d := &Dispatcher{repo: repo, inserter: inserter, batch: 10, maxAttempts: 5, claimLease: 5 * time.Minute, sendTimeout: 10 * time.Second}
|
||||
if opts != nil {
|
||||
if opts.Batch < 0 || opts.MaxAttempts < 0 || opts.ClaimLease < 0 || opts.SendTimeout < 0 {
|
||||
return nil, errors.New("faqtable dispatcher options are invalid")
|
||||
}
|
||||
if opts.Batch > 0 {
|
||||
d.batch = opts.Batch
|
||||
}
|
||||
if opts.MaxAttempts > 0 {
|
||||
d.maxAttempts = opts.MaxAttempts
|
||||
}
|
||||
if opts.ClaimLease > 0 {
|
||||
d.claimLease = opts.ClaimLease
|
||||
}
|
||||
if opts.SendTimeout > 0 {
|
||||
d.sendTimeout = opts.SendTimeout
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) {
|
||||
var stats DispatcherStats
|
||||
if err := ctx.Err(); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
items, err := d.repo.Claim(ctx, d.batch, d.maxAttempts, time.Now().Add(-d.claimLease))
|
||||
if err != nil {
|
||||
return stats, errors.New("faqtable dispatcher claim failed")
|
||||
}
|
||||
stats.Claimed = len(items)
|
||||
for _, item := range items {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
itemCtx, cancel := context.WithTimeout(ctx, d.sendTimeout)
|
||||
recordID, insertErr := d.inserter.InsertFields(itemCtx, item.Row.ToFields())
|
||||
cancel()
|
||||
if insertErr != nil || strings.TrimSpace(recordID) == "" {
|
||||
if err := d.repo.MarkFailed(ctx, item.CaseID, FailureCodeRemoteInsertFailed); err != nil {
|
||||
return stats, errors.New("faqtable dispatcher mark failed failed")
|
||||
}
|
||||
stats.Failed++
|
||||
continue
|
||||
}
|
||||
if err := d.repo.MarkExported(ctx, item.CaseID, recordID); err != nil {
|
||||
return stats, errors.New("faqtable dispatcher mark exported failed")
|
||||
}
|
||||
stats.Exported++
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func isNil(value interface{}) bool {
|
||||
if value == nil {
|
||||
return true
|
||||
}
|
||||
v := reflect.ValueOf(value)
|
||||
switch v.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
||||
return v.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package faqtable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dispatcherRepoStub struct {
|
||||
items []PendingExport
|
||||
exported map[string]string
|
||||
failed map[string]string
|
||||
}
|
||||
|
||||
func (s *dispatcherRepoStub) Claim(context.Context, int, int, time.Time) ([]PendingExport, error) {
|
||||
items := s.items
|
||||
s.items = nil
|
||||
return items, nil
|
||||
}
|
||||
func (s *dispatcherRepoStub) MarkExported(_ context.Context, id, recordID string) error {
|
||||
if s.exported == nil {
|
||||
s.exported = map[string]string{}
|
||||
}
|
||||
s.exported[id] = recordID
|
||||
return nil
|
||||
}
|
||||
func (s *dispatcherRepoStub) MarkFailed(_ context.Context, id, code string) error {
|
||||
if s.failed == nil {
|
||||
s.failed = map[string]string{}
|
||||
}
|
||||
s.failed[id] = code
|
||||
return nil
|
||||
}
|
||||
|
||||
type fieldsInserterStub struct {
|
||||
fields map[string]interface{}
|
||||
id string
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *fieldsInserterStub) InsertFields(_ context.Context, fields map[string]interface{}) (string, error) {
|
||||
s.fields = fields
|
||||
return s.id, s.err
|
||||
}
|
||||
|
||||
func TestDispatcherExportsFAQAndPersistsRecordID(t *testing.T) {
|
||||
repo := &dispatcherRepoStub{items: []PendingExport{{
|
||||
CaseID: "case-1",
|
||||
Row: Row{StandardQuestion: "中文问题", OriginalQuestion: "中文问题", AskerName: "张三", AskerUnionID: "union-1"},
|
||||
}}}
|
||||
inserter := &fieldsInserterStub{id: "record-1"}
|
||||
d, err := NewDispatcher(repo, inserter, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stats.Claimed != 1 || stats.Exported != 1 || stats.Failed != 0 {
|
||||
t.Fatalf("stats=%+v", stats)
|
||||
}
|
||||
if repo.exported["case-1"] != "record-1" || inserter.fields[FieldLanguage] != "Chinese" {
|
||||
t.Fatalf("exported=%#v fields=%#v", repo.exported, inserter.fields)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatcherPersistsOnlyStableFAQFailureCode(t *testing.T) {
|
||||
repo := &dispatcherRepoStub{items: []PendingExport{{CaseID: "case-2", Row: Row{StandardQuestion: "secret question", OriginalQuestion: "secret question"}}}}
|
||||
inserter := &fieldsInserterStub{err: errors.New("token=secret raw question=secret question")}
|
||||
d, err := NewDispatcher(repo, inserter, &DispatcherOptions{SendTimeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stats, err := d.RunOnce(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stats.Failed != 1 || repo.failed["case-2"] != FailureCodeRemoteInsertFailed {
|
||||
t.Fatalf("stats=%+v failed=%#v", stats, repo.failed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package faqtable
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Verified DingTalk Notable FAQ field IDs.
|
||||
const (
|
||||
FieldStandardQuestion = "01ZM8y7" // text: 标准问题(必填)
|
||||
FieldOriginalQuestion = "fj3JQ1C" // text: 原始问题
|
||||
FieldLanguage = "07YYagS" // text: 语言
|
||||
FieldAsker = "Eu7gkKu" // user: 提问人
|
||||
)
|
||||
|
||||
type Row struct {
|
||||
StandardQuestion string
|
||||
OriginalQuestion string
|
||||
AskerName string
|
||||
AskerUnionID string
|
||||
}
|
||||
|
||||
func (r Row) ToFields() map[string]interface{} {
|
||||
fields := map[string]interface{}{
|
||||
FieldStandardQuestion: safeText(r.StandardQuestion),
|
||||
FieldOriginalQuestion: safeText(r.OriginalQuestion),
|
||||
FieldLanguage: DetectLanguage(r.OriginalQuestion),
|
||||
}
|
||||
if unionID := strings.TrimSpace(r.AskerUnionID); unionID != "" {
|
||||
fields[FieldAsker] = []interface{}{map[string]interface{}{
|
||||
"name": strings.TrimSpace(r.AskerName),
|
||||
"unionId": unionID,
|
||||
}}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func safeText(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.ContainsRune("=+-@", rune(value[0])) {
|
||||
return "'" + value
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func DetectLanguage(value string) string {
|
||||
if strings.Contains(value, "日本語") {
|
||||
return "Japanese"
|
||||
}
|
||||
var hasHan, hasKana, hasHangul, hasLatin, hasSpanish bool
|
||||
for _, r := range value {
|
||||
switch {
|
||||
case unicode.In(r, unicode.Hiragana, unicode.Katakana):
|
||||
hasKana = true
|
||||
case unicode.In(r, unicode.Hangul):
|
||||
hasHangul = true
|
||||
case unicode.In(r, unicode.Han):
|
||||
hasHan = true
|
||||
case strings.ContainsRune("áéíóúüñÁÉÍÓÚÜÑ¿¡", r):
|
||||
hasSpanish = true
|
||||
case unicode.In(r, unicode.Latin):
|
||||
hasLatin = true
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case hasKana:
|
||||
return "Japanese"
|
||||
case hasHangul:
|
||||
return "Korean"
|
||||
case hasHan:
|
||||
return "Chinese"
|
||||
case hasSpanish:
|
||||
return "Spanish"
|
||||
case hasLatin:
|
||||
return "English"
|
||||
default:
|
||||
return "Other"
|
||||
}
|
||||
}
|
||||
|
||||
type RecordLinkBuilder struct {
|
||||
baseID string
|
||||
sheetID string
|
||||
viewID string
|
||||
}
|
||||
|
||||
func NewRecordLinkBuilder(baseID, sheetID, viewID string) (*RecordLinkBuilder, error) {
|
||||
baseID = strings.TrimSpace(baseID)
|
||||
sheetID = strings.TrimSpace(sheetID)
|
||||
viewID = strings.TrimSpace(viewID)
|
||||
if baseID == "" || sheetID == "" || viewID == "" {
|
||||
return nil, errors.New("faq record link configuration is incomplete")
|
||||
}
|
||||
return &RecordLinkBuilder{baseID: baseID, sheetID: sheetID, viewID: viewID}, nil
|
||||
}
|
||||
|
||||
func (b *RecordLinkBuilder) Build(recordID string) (string, error) {
|
||||
if b == nil {
|
||||
return "", errors.New("faq record link builder is unavailable")
|
||||
}
|
||||
recordID = strings.TrimSpace(recordID)
|
||||
if recordID == "" {
|
||||
return "", errors.New("faq record id is required")
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("dentryUuid", b.baseID)
|
||||
q.Set("rowId", recordID)
|
||||
q.Set("sheetId", b.sheetID)
|
||||
q.Set("viewId", b.viewID)
|
||||
return (&url.URL{Scheme: "https", Host: "docs.dingtalk.com", Path: "/notable/record", RawQuery: q.Encode()}).String(), nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package faqtable
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRowToFieldsUsesVerifiedFAQContract(t *testing.T) {
|
||||
fields := (Row{
|
||||
StandardQuestion: "Nova5I支持哪些通信协议?",
|
||||
OriginalQuestion: "Nova5I支持哪些通信协议?",
|
||||
AskerName: "测试用户",
|
||||
AskerUnionID: "union-1",
|
||||
}).ToFields()
|
||||
|
||||
if got := fields[FieldStandardQuestion]; got != "Nova5I支持哪些通信协议?" {
|
||||
t.Fatalf("standard question = %v", got)
|
||||
}
|
||||
if got := fields[FieldOriginalQuestion]; got != "Nova5I支持哪些通信协议?" {
|
||||
t.Fatalf("original question = %v", got)
|
||||
}
|
||||
if got := fields[FieldLanguage]; got != "Chinese" {
|
||||
t.Fatalf("language = %v, want Chinese", got)
|
||||
}
|
||||
users, ok := fields[FieldAsker].([]interface{})
|
||||
if !ok || len(users) != 1 {
|
||||
t.Fatalf("asker shape = %#v", fields[FieldAsker])
|
||||
}
|
||||
user, ok := users[0].(map[string]interface{})
|
||||
if !ok || user["name"] != "测试用户" || user["unionId"] != "union-1" {
|
||||
t.Fatalf("asker = %#v", users[0])
|
||||
}
|
||||
if len(fields) != 4 {
|
||||
t.Fatalf("field count = %d, want exactly four", len(fields))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsOmitsAskerWithoutUnionID(t *testing.T) {
|
||||
fields := (Row{StandardQuestion: "Question", OriginalQuestion: "Question", AskerName: "name"}).ToFields()
|
||||
if _, ok := fields[FieldAsker]; ok {
|
||||
t.Fatal("asker must be omitted without unionId")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectLanguageUsesFAQEnglishEnums(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"中文问题": "Chinese",
|
||||
"日本語の質問": "Japanese",
|
||||
"한국어 질문": "Korean",
|
||||
"English question": "English",
|
||||
"12345": "Other",
|
||||
"日本語和漢字 mixed question": "Japanese",
|
||||
}
|
||||
for input, want := range cases {
|
||||
if got := DetectLanguage(input); got != want {
|
||||
t.Errorf("DetectLanguage(%q)=%q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowToFieldsProtectsFormulaInjection(t *testing.T) {
|
||||
fields := (Row{StandardQuestion: "=cmd", OriginalQuestion: "+cmd"}).ToFields()
|
||||
if fields[FieldStandardQuestion] != "'=cmd" || fields[FieldOriginalQuestion] != "'+cmd" {
|
||||
t.Fatalf("fields not sanitised: %#v", fields)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordLinkBuilderUsesReturnedRecordIDAsRowID(t *testing.T) {
|
||||
builder, err := NewRecordLinkBuilder("base+id", "sheet/id", "view id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := builder.Build("record&id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, err := url.Parse(got)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Scheme != "https" || parsed.Host != "docs.dingtalk.com" || parsed.Path != "/notable/record" {
|
||||
t.Fatalf("unexpected link: %s", got)
|
||||
}
|
||||
q := parsed.Query()
|
||||
if q.Get("dentryUuid") != "base+id" || q.Get("rowId") != "record&id" || q.Get("sheetId") != "sheet/id" || q.Get("viewId") != "view id" {
|
||||
t.Fatalf("unexpected query: %#v", q)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordLinkBuilderRejectsMissingConfigOrRecordID(t *testing.T) {
|
||||
for _, args := range [][3]string{{"", "s", "v"}, {"b", "", "v"}, {"b", "s", ""}} {
|
||||
if _, err := NewRecordLinkBuilder(args[0], args[1], args[2]); err == nil {
|
||||
t.Fatalf("expected error for %#v", args)
|
||||
}
|
||||
}
|
||||
builder, err := NewRecordLinkBuilder("b", "s", "v")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := builder.Build(" "); err == nil || strings.Contains(err.Error(), "b") {
|
||||
t.Fatalf("expected sanitised missing record error, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user