feat: integrate ChatBot provider and docreader
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Config 加密服务配置结构
|
||||
type Config struct {
|
||||
// MasterKey 主密钥,用于派生加密密钥
|
||||
// 可以从环境变量或配置文件中读取
|
||||
MasterKey string `json:"master_key" yaml:"master_key" env:"CRYPTO_MASTER_KEY"`
|
||||
|
||||
// Salt 盐值,用于密钥派生
|
||||
// 如果为空,将自动生成随机盐值
|
||||
Salt string `json:"salt" yaml:"salt" env:"CRYPTO_SALT"`
|
||||
|
||||
// SaltLength 盐值长度(当Salt为空时使用)
|
||||
SaltLength int `json:"salt_length" yaml:"salt_length" env:"CRYPTO_SALT_LENGTH" default:"16"`
|
||||
|
||||
// KeyDerivationIterations PBKDF2迭代次数
|
||||
KeyDerivationIterations int `json:"key_derivation_iterations" yaml:"key_derivation_iterations" env:"CRYPTO_ITERATIONS" default:"10000"`
|
||||
|
||||
// KeyLength 派生密钥长度
|
||||
KeyLength int `json:"key_length" yaml:"key_length" env:"CRYPTO_KEY_LENGTH" default:"32"`
|
||||
}
|
||||
|
||||
// DefaultConfig 返回默认配置
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
MasterKey: "",
|
||||
Salt: "",
|
||||
SaltLength: 16,
|
||||
KeyDerivationIterations: 10000,
|
||||
KeyLength: 32,
|
||||
}
|
||||
}
|
||||
|
||||
// LoadConfigFromEnv 从环境变量加载配置
|
||||
func LoadConfigFromEnv() *Config {
|
||||
config := DefaultConfig()
|
||||
|
||||
// 从环境变量读取主密钥
|
||||
if masterKey := os.Getenv("CRYPTO_MASTER_KEY"); masterKey != "" {
|
||||
config.MasterKey = masterKey
|
||||
}
|
||||
|
||||
// 从环境变量读取盐值
|
||||
if salt := os.Getenv("CRYPTO_SALT"); salt != "" {
|
||||
config.Salt = salt
|
||||
}
|
||||
|
||||
// 从环境变量读取盐值长度
|
||||
if saltLengthStr := os.Getenv("CRYPTO_SALT_LENGTH"); saltLengthStr != "" {
|
||||
if saltLength, err := strconv.Atoi(saltLengthStr); err == nil && saltLength >= 8 {
|
||||
config.SaltLength = saltLength
|
||||
}
|
||||
}
|
||||
|
||||
// 从环境变量读取迭代次数
|
||||
if iterationsStr := os.Getenv("CRYPTO_ITERATIONS"); iterationsStr != "" {
|
||||
if iterations, err := strconv.Atoi(iterationsStr); err == nil && iterations > 0 {
|
||||
config.KeyDerivationIterations = iterations
|
||||
}
|
||||
}
|
||||
|
||||
// 从环境变量读取密钥长度
|
||||
if keyLengthStr := os.Getenv("CRYPTO_KEY_LENGTH"); keyLengthStr != "" {
|
||||
if keyLength, err := strconv.Atoi(keyLengthStr); err == nil && keyLength >= 16 {
|
||||
config.KeyLength = keyLength
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
// Validate 验证配置是否有效
|
||||
func (c *Config) Validate() error {
|
||||
if c.MasterKey == "" {
|
||||
return fmt.Errorf("master key cannot be empty")
|
||||
}
|
||||
|
||||
if c.SaltLength < 8 {
|
||||
return fmt.Errorf("salt length must be at least 8 bytes")
|
||||
}
|
||||
|
||||
if c.KeyDerivationIterations < 1000 {
|
||||
return fmt.Errorf("key derivation iterations must be at least 1000")
|
||||
}
|
||||
|
||||
if c.KeyLength < 16 {
|
||||
return fmt.Errorf("key length must be at least 16 bytes")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSaltBytes 获取盐值的字节数组形式
|
||||
func (c *Config) GetSaltBytes() ([]byte, error) {
|
||||
if c.Salt != "" {
|
||||
// 如果配置了盐值,解码Base64格式
|
||||
saltBytes, err := base64.StdEncoding.DecodeString(c.Salt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode salt from base64: %w", err)
|
||||
}
|
||||
return saltBytes, nil
|
||||
}
|
||||
|
||||
// 如果没有配置盐值,生成随机盐值
|
||||
salt, err := GenerateRandomSalt(c.SaltLength)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate random salt: %w", err)
|
||||
}
|
||||
|
||||
return salt, nil
|
||||
}
|
||||
|
||||
// NewCryptoServiceFromConfig 从配置创建加密服务
|
||||
func NewCryptoServiceFromConfig(config *Config) (*CryptoService, error) {
|
||||
if err := config.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
saltBytes, err := config.GetSaltBytes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get salt bytes: %w", err)
|
||||
}
|
||||
|
||||
return NewCryptoService(config.MasterKey, saltBytes)
|
||||
}
|
||||
|
||||
// ExampleConfigUsage 展示配置使用示例
|
||||
func ExampleConfigUsage() {
|
||||
fmt.Println("=== 配置使用示例 ===")
|
||||
|
||||
// 方法1: 手动创建配置
|
||||
manualConfig := &Config{
|
||||
MasterKey: "my-secret-master-key",
|
||||
Salt: "", // 自动生成盐值
|
||||
SaltLength: 16,
|
||||
KeyDerivationIterations: 10000,
|
||||
KeyLength: 32,
|
||||
}
|
||||
|
||||
cryptoService1, err := NewCryptoServiceFromConfig(manualConfig)
|
||||
if err != nil {
|
||||
fmt.Printf("手动配置创建失败: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("手动配置创建成功")
|
||||
_ = cryptoService1
|
||||
}
|
||||
|
||||
// 方法2: 从环境变量加载配置
|
||||
// 首先设置环境变量
|
||||
os.Setenv("CRYPTO_MASTER_KEY", "env-master-key")
|
||||
os.Setenv("CRYPTO_SALT", base64.StdEncoding.EncodeToString([]byte("env-salt-123456")))
|
||||
os.Setenv("CRYPTO_SALT_LENGTH", "16")
|
||||
os.Setenv("CRYPTO_ITERATIONS", "10000")
|
||||
os.Setenv("CRYPTO_KEY_LENGTH", "32")
|
||||
|
||||
envConfig := LoadConfigFromEnv()
|
||||
cryptoService2, err := NewCryptoServiceFromConfig(envConfig)
|
||||
if err != nil {
|
||||
fmt.Printf("环境变量配置创建失败: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("环境变量配置创建成功")
|
||||
_ = cryptoService2
|
||||
}
|
||||
|
||||
// 清理环境变量
|
||||
os.Unsetenv("CRYPTO_MASTER_KEY")
|
||||
os.Unsetenv("CRYPTO_SALT")
|
||||
os.Unsetenv("CRYPTO_SALT_LENGTH")
|
||||
os.Unsetenv("CRYPTO_ITERATIONS")
|
||||
os.Unsetenv("CRYPTO_KEY_LENGTH")
|
||||
}
|
||||
|
||||
// GenerateConfigExample 生成配置示例
|
||||
func GenerateConfigExample() {
|
||||
fmt.Println("\n=== 配置生成示例 ===")
|
||||
|
||||
// 生成随机主密钥
|
||||
masterKey, err := GenerateRandomKey(32)
|
||||
if err != nil {
|
||||
fmt.Printf("生成主密钥失败: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 生成随机盐值
|
||||
salt, err := GenerateRandomSalt(16)
|
||||
if err != nil {
|
||||
fmt.Printf("生成盐值失败: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
saltBase64 := base64.StdEncoding.EncodeToString(salt)
|
||||
|
||||
fmt.Println("生成的配置示例:")
|
||||
fmt.Printf("CRYPTO_MASTER_KEY=%s\n", masterKey)
|
||||
fmt.Printf("CRYPTO_SALT=%s\n", saltBase64)
|
||||
fmt.Printf("CRYPTO_SALT_LENGTH=16\n")
|
||||
fmt.Printf("CRYPTO_ITERATIONS=10000\n")
|
||||
fmt.Printf("CRYPTO_KEY_LENGTH=32\n")
|
||||
|
||||
fmt.Println("\nYAML格式配置示例:")
|
||||
fmt.Printf(`master_key: %s
|
||||
salt: %s
|
||||
salt_length: 16
|
||||
key_derivation_iterations: 10000
|
||||
key_length: 32
|
||||
`, masterKey, saltBase64)
|
||||
|
||||
fmt.Println("\nJSON格式配置示例:")
|
||||
fmt.Printf(`{
|
||||
"master_key": "%s",
|
||||
"salt": "%s",
|
||||
"salt_length": 16,
|
||||
"key_derivation_iterations": 10000,
|
||||
"key_length": 32
|
||||
}
|
||||
`, masterKey, saltBase64)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
// CryptoService 提供密钥加密解密服务
|
||||
type CryptoService struct {
|
||||
masterKey []byte
|
||||
salt []byte
|
||||
}
|
||||
|
||||
// NewCryptoService 创建新的加密服务实例
|
||||
// masterKey: 主密钥,用于派生加密密钥
|
||||
// salt: 盐值,用于密钥派生,如果为空则生成随机盐
|
||||
func NewCryptoService(masterKey string, salt []byte) (*CryptoService, error) {
|
||||
if masterKey == "" {
|
||||
return nil, errors.New("master key cannot be empty")
|
||||
}
|
||||
|
||||
// 如果未提供盐值,生成随机盐
|
||||
if salt == nil || len(salt) == 0 {
|
||||
salt = make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate salt: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &CryptoService{
|
||||
masterKey: []byte(masterKey),
|
||||
salt: salt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// deriveKey 使用PBKDF2派生加密密钥
|
||||
func (cs *CryptoService) deriveKey() []byte {
|
||||
return pbkdf2.Key(cs.masterKey, cs.salt, 10000, 32, sha256.New)
|
||||
}
|
||||
|
||||
// Encrypt 加密数据
|
||||
func (cs *CryptoService) Encrypt(plaintext []byte) (string, error) {
|
||||
if len(plaintext) == 0 {
|
||||
return "", errors.New("plaintext cannot be empty")
|
||||
}
|
||||
|
||||
key := cs.deriveKey()
|
||||
|
||||
// 创建AES块密码
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create cipher: %w", err)
|
||||
}
|
||||
|
||||
// 生成随机IV
|
||||
iv := make([]byte, aes.BlockSize)
|
||||
if _, err := rand.Read(iv); err != nil {
|
||||
return "", fmt.Errorf("failed to generate IV: %w", err)
|
||||
}
|
||||
|
||||
// 使用CTR模式加密
|
||||
stream := cipher.NewCTR(block, iv)
|
||||
ciphertext := make([]byte, len(plaintext))
|
||||
stream.XORKeyStream(ciphertext, plaintext)
|
||||
|
||||
// 组合IV和密文
|
||||
result := make([]byte, len(iv)+len(ciphertext))
|
||||
copy(result[:aes.BlockSize], iv)
|
||||
copy(result[aes.BlockSize:], ciphertext)
|
||||
|
||||
// 返回Base64编码的结果
|
||||
return base64.StdEncoding.EncodeToString(result), nil
|
||||
}
|
||||
|
||||
// Decrypt 解密数据
|
||||
func (cs *CryptoService) Decrypt(encryptedData string) ([]byte, error) {
|
||||
if encryptedData == "" {
|
||||
return nil, errors.New("encrypted data cannot be empty")
|
||||
}
|
||||
|
||||
// 解码Base64数据
|
||||
data, err := base64.StdEncoding.DecodeString(encryptedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode base64: %w", err)
|
||||
}
|
||||
|
||||
if len(data) < aes.BlockSize {
|
||||
return nil, errors.New("encrypted data too short")
|
||||
}
|
||||
|
||||
key := cs.deriveKey()
|
||||
|
||||
// 创建AES块密码
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create cipher: %w", err)
|
||||
}
|
||||
|
||||
// 提取IV和密文
|
||||
iv := data[:aes.BlockSize]
|
||||
ciphertext := data[aes.BlockSize:]
|
||||
|
||||
// 使用CTR模式解密
|
||||
stream := cipher.NewCTR(block, iv)
|
||||
plaintext := make([]byte, len(ciphertext))
|
||||
stream.XORKeyStream(plaintext, ciphertext)
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// EncryptString 加密字符串
|
||||
func (cs *CryptoService) EncryptString(plaintext string) (string, error) {
|
||||
return cs.Encrypt([]byte(plaintext))
|
||||
}
|
||||
|
||||
// DecryptString 解密字符串
|
||||
func (cs *CryptoService) DecryptString(encryptedData string) (string, error) {
|
||||
plaintext, err := cs.Decrypt(encryptedData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
// GetSalt 获取当前使用的盐值
|
||||
func (cs *CryptoService) GetSalt() []byte {
|
||||
return cs.salt
|
||||
}
|
||||
|
||||
// GenerateRandomKey 生成随机密钥
|
||||
func GenerateRandomKey(length int) (string, error) {
|
||||
if length < 16 {
|
||||
return "", errors.New("key length must be at least 16 bytes")
|
||||
}
|
||||
|
||||
key := make([]byte, length)
|
||||
if _, err := rand.Read(key); err != nil {
|
||||
return "", fmt.Errorf("failed to generate random key: %w", err)
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// GenerateRandomSalt 生成随机盐值
|
||||
func GenerateRandomSalt(length int) ([]byte, error) {
|
||||
if length < 8 {
|
||||
return nil, errors.New("salt length must be at least 8 bytes")
|
||||
}
|
||||
|
||||
salt := make([]byte, length)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate random salt: %w", err)
|
||||
}
|
||||
|
||||
return salt, nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package docparser
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
@@ -27,6 +28,7 @@ func RegisterEngine(e EngineRegistration) {
|
||||
func init() {
|
||||
RegisterEngine(&builtinEngine{})
|
||||
RegisterEngine(&simpleEngine{})
|
||||
RegisterEngine(&weKnoraCloudEngine{})
|
||||
RegisterEngine(&mineruEngine{})
|
||||
RegisterEngine(&mineruCloudEngine{})
|
||||
}
|
||||
@@ -54,6 +56,9 @@ func (e *builtinEngine) CheckAvailable(docreaderConnected bool, _ map[string]str
|
||||
// SimpleEngineName is the engine name for Go-native simple format handling.
|
||||
const SimpleEngineName = "simple"
|
||||
|
||||
// WeKnoraCloudEngineName is the engine name for WeKnoraCloud-backed document parsing.
|
||||
const WeKnoraCloudEngineName = "weknoracloud"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// simple — Go handles md/txt/csv natively, no external service needed.
|
||||
// Distinct from docreader's "builtin" which uses Python libraries for
|
||||
@@ -73,6 +78,24 @@ func (e *simpleEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// weknoracloud — Tenant-scoped WeKnoraCloud docreader with signed requests.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type weKnoraCloudEngine struct{}
|
||||
|
||||
func (e *weKnoraCloudEngine) Name() string { return WeKnoraCloudEngineName }
|
||||
func (e *weKnoraCloudEngine) Description() string { return "WeKnoraCloud document reader" }
|
||||
func (e *weKnoraCloudEngine) FileTypes(_ bool) []string {
|
||||
return weKnoraCloudSupportedFileTypes()
|
||||
}
|
||||
func (e *weKnoraCloudEngine) CheckAvailable(docreaderConnected bool, overrides map[string]string) (bool, string) {
|
||||
if docreaderConnected && isWeKnoraCloudDocReaderAddr(overrides["docreader_addr"]) {
|
||||
return true, ""
|
||||
}
|
||||
return false, "WeKnoraCloud document reader is not initialized"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// mineru — Go-native, calls self-hosted MinerU API directly
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -169,3 +192,7 @@ func ListAllEngines(docreaderConnected bool, overrides map[string]string, remote
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func isWeKnoraCloudDocReaderAddr(addr string) bool {
|
||||
return strings.TrimSuffix(strings.TrimSpace(addr), "/") == strings.TrimRight(provider.WeKnoraCloudBaseURL, "/")+"/api/v1/doc/reader"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// WeKnoraCloudSignedDocumentReader implements the docreader HTTP protocol with WeKnoraCloud signing.
|
||||
type WeKnoraCloudSignedDocumentReader struct {
|
||||
baseURL string
|
||||
appID string
|
||||
apiKey string
|
||||
client *http.Client
|
||||
initialPollInterval time.Duration
|
||||
maxPollInterval time.Duration
|
||||
pollTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewWeKnoraCloudSignedDocumentReader(baseURL, appID, apiKey string) (*WeKnoraCloudSignedDocumentReader, error) {
|
||||
baseURL = strings.TrimSuffix(strings.TrimSpace(baseURL), "/")
|
||||
if baseURL == "" {
|
||||
return nil, fmt.Errorf("docreader base URL is required")
|
||||
}
|
||||
if appID == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud appID is required")
|
||||
}
|
||||
if apiKey == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud apiKey is required")
|
||||
}
|
||||
return &WeKnoraCloudSignedDocumentReader{
|
||||
baseURL: baseURL,
|
||||
appID: appID,
|
||||
apiKey: apiKey,
|
||||
initialPollInterval: 500 * time.Millisecond,
|
||||
maxPollInterval: 10 * time.Second,
|
||||
pollTimeout: 20 * time.Minute,
|
||||
client: &http.Client{
|
||||
Timeout: 500 * time.Minute,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
MaxIdleConnsPerHost: 5,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) Reconnect(addr string) error {
|
||||
p.baseURL = strings.TrimSuffix(strings.TrimSpace(addr), "/")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) IsConnected() bool { return p.baseURL != "" }
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
|
||||
if !p.IsConnected() {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
return []types.ParserEngineInfo{{
|
||||
Name: WeKnoraCloudEngineName,
|
||||
Description: "WeKnoraCloud signed docreader",
|
||||
FileTypes: weKnoraCloudSupportedFileTypes(),
|
||||
Available: true,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
if !p.IsConnected() {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
body := httpReadRequest{
|
||||
FileName: req.FileName,
|
||||
FileType: req.FileType,
|
||||
URL: req.URL,
|
||||
Title: req.Title,
|
||||
RequestID: req.RequestID,
|
||||
Config: &httpReadConfig{
|
||||
ParserEngine: req.ParserEngine,
|
||||
ParserEngineOverrides: req.ParserEngineOverrides,
|
||||
},
|
||||
}
|
||||
if len(req.FileContent) > 0 {
|
||||
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
|
||||
}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http marshal read request: %w", err)
|
||||
}
|
||||
httpReq, err := p.newSignedRequest(ctx, http.MethodPost, p.baseURL, jsonBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := p.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http read failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
var submit weKnoraCloudAsyncSubmitResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&submit); err != nil {
|
||||
return nil, fmt.Errorf("http decode read submit response: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(submit.TaskID) == "" {
|
||||
return nil, fmt.Errorf("weknoracloud docreader submit response missing task_id")
|
||||
}
|
||||
return p.pollTaskResult(ctx, submit.TaskID)
|
||||
}
|
||||
|
||||
type weKnoraCloudAsyncSubmitResponse struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type weKnoraCloudAsyncTaskResponse struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Progress float64 `json:"progress"`
|
||||
Result *httpReadResponse `json:"result"`
|
||||
Error string `json:"error"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
func weKnoraCloudSupportedFileTypes() []string {
|
||||
seen := map[string]struct{}{}
|
||||
var fileTypes []string
|
||||
for _, engine := range localEngines {
|
||||
if engine.Name() == WeKnoraCloudEngineName {
|
||||
continue
|
||||
}
|
||||
for _, fileType := range engine.FileTypes(true) {
|
||||
if _, ok := seen[fileType]; ok {
|
||||
continue
|
||||
}
|
||||
seen[fileType] = struct{}{}
|
||||
fileTypes = append(fileTypes, fileType)
|
||||
}
|
||||
}
|
||||
sort.Strings(fileTypes)
|
||||
return fileTypes
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) pollTaskResult(ctx context.Context, taskID string) (*types.ReadResult, error) {
|
||||
pollCtx := ctx
|
||||
if _, ok := ctx.Deadline(); !ok && p.pollTimeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
pollCtx, cancel = context.WithTimeout(ctx, p.pollTimeout)
|
||||
defer cancel()
|
||||
}
|
||||
statusURL := strings.TrimSuffix(p.baseURL, "/reader") + "/" + taskID
|
||||
currentInterval := p.initialPollInterval
|
||||
for {
|
||||
httpReq, err := p.newSignedRequest(pollCtx, http.MethodGet, statusURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := p.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http poll task failed: %w", err)
|
||||
}
|
||||
var taskResp weKnoraCloudAsyncTaskResponse
|
||||
func() {
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("http poll task status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
return
|
||||
}
|
||||
if decodeErr := json.NewDecoder(resp.Body).Decode(&taskResp); decodeErr != nil {
|
||||
err = fmt.Errorf("http decode task response: %w", decodeErr)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch taskResp.Status {
|
||||
case "completed":
|
||||
if taskResp.Result == nil {
|
||||
return &types.ReadResult{}, nil
|
||||
}
|
||||
return fromHTTPReadResponse(taskResp.Result), nil
|
||||
case "failed":
|
||||
if taskResp.Error != "" {
|
||||
return nil, fmt.Errorf("weknoracloud docreader task failed: %s", taskResp.Error)
|
||||
}
|
||||
return nil, fmt.Errorf("weknoracloud docreader task failed: %s", taskResp.Message)
|
||||
case "cancelled":
|
||||
if taskResp.Error != "" {
|
||||
return nil, fmt.Errorf("weknoracloud docreader task cancelled: %s", taskResp.Error)
|
||||
}
|
||||
return nil, fmt.Errorf("weknoracloud docreader task cancelled")
|
||||
}
|
||||
if err := pollCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Exponential backoff: multiply by 1.5 each time, cap at maxPollInterval
|
||||
select {
|
||||
case <-pollCtx.Done():
|
||||
return nil, pollCtx.Err()
|
||||
case <-time.After(currentInterval):
|
||||
// Update interval for next iteration
|
||||
nextInterval := time.Duration(float64(currentInterval) * 1.5)
|
||||
if nextInterval > p.maxPollInterval {
|
||||
nextInterval = p.maxPollInterval
|
||||
}
|
||||
currentInterval = nextInterval
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudSignedDocumentReader) newSignedRequest(ctx context.Context, method, url string, body []byte) (*http.Request, error) {
|
||||
requestID := uuid.New().String()
|
||||
if len(body) == 0 {
|
||||
body = []byte("{}")
|
||||
}
|
||||
httpReq, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http new request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.ContentLength = int64(len(body))
|
||||
for k, v := range utils.Sign(p.appID, p.apiKey, requestID, string(body)) {
|
||||
httpReq.Header.Set(k, v)
|
||||
}
|
||||
return httpReq, nil
|
||||
}
|
||||
Reference in New Issue
Block a user