init commit

This commit is contained in:
wizardchen
2025-08-05 15:08:07 +08:00
commit 56eb2bce33
282 changed files with 49077 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
package common
import (
"log"
"github.com/Tencent/WeKnora/internal/config"
"github.com/hibiken/asynq"
)
// client is the global asyncq client instance
var client *asynq.Client
// InitAsyncq initializes the asyncq client with configuration
// It creates a new client and starts the server in a goroutine
func InitAsyncq(config *config.Config) error {
cfg := config.Asynq
client = asynq.NewClient(asynq.RedisClientOpt{
Addr: cfg.Addr,
Username: cfg.Username,
Password: cfg.Password,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
})
go run(cfg)
return nil
}
// GetAsyncqClient returns the global asyncq client instance
func GetAsyncqClient() *asynq.Client {
return client
}
// handleFunc stores registered task handlers
var handleFunc = map[string]asynq.HandlerFunc{}
// RegisterHandlerFunc registers a handler function for a specific task type
func RegisterHandlerFunc(taskType string, handlerFunc asynq.HandlerFunc) {
handleFunc[taskType] = handlerFunc
}
// run starts the asyncq server with the given configuration
// It creates a new server, sets up handlers, and runs the server
func run(config *config.AsynqConfig) {
srv := asynq.NewServer(
asynq.RedisClientOpt{
Addr: config.Addr,
Username: config.Username,
Password: config.Password,
ReadTimeout: config.ReadTimeout,
WriteTimeout: config.WriteTimeout,
},
asynq.Config{
Concurrency: config.Concurrency,
Queues: map[string]int{
"critical": 6, // Highest priority queue
"default": 3, // Default priority queue
"low": 1, // Lowest priority queue
},
},
)
// Create a new mux and register all handlers
mux := asynq.NewServeMux()
for typ, handler := range handleFunc {
mux.HandleFunc(typ, handler)
}
// Start the server
if err := srv.Run(mux); err != nil {
log.Fatalf("could not run server: %v", err)
}
}
+75
View File
@@ -0,0 +1,75 @@
package common
import (
"encoding/json"
"maps"
"regexp"
"slices"
"strings"
)
// ToInterfaceSlice converts a slice of strings to a slice of empty interfaces.
func ToInterfaceSlice[T any](slice []T) []interface{} {
interfaceSlice := make([]interface{}, len(slice))
for i, v := range slice {
interfaceSlice[i] = v
}
return interfaceSlice
}
// []string -> string, " join, space separated
func StringSliceJoin(slice []string) string {
result := make([]string, len(slice))
for i, v := range slice {
result[i] = `"` + v + `"`
}
return strings.Join(result, " ")
}
func GetAttrs[A, B any](extract func(A) B, attrs ...A) []B {
result := make([]B, len(attrs))
for i, attr := range attrs {
result[i] = extract(attr)
}
return result
}
// Deduplicate removes duplicates from a slice based on a key function
// T: the type of elements in the slice
// K: the type of key used for deduplication
func Deduplicate[T any, K comparable](keyFunc func(T) K, items ...T) []T {
seen := make(map[K]T)
for _, item := range items {
key := keyFunc(item)
if _, exists := seen[key]; !exists {
seen[key] = item
}
}
return slices.Collect(maps.Values(seen))
}
// ParseLLMJsonResponse parses a JSON response from LLM, handling cases where JSON is wrapped in code blocks.
// This is useful when LLMs return responses like:
// ```json
// {"key": "value"}
// ```
// or regular JSON responses directly.
func ParseLLMJsonResponse(content string, target interface{}) error {
// First, try to parse directly as JSON
err := json.Unmarshal([]byte(content), target)
if err == nil {
return nil
}
// If direct parsing fails, try to extract JSON from code blocks
re := regexp.MustCompile("```(?:json)?\\s*([\\s\\S]*?)```")
matches := re.FindStringSubmatch(content)
if len(matches) >= 2 {
// Extract the JSON content within the code block
jsonContent := strings.TrimSpace(matches[1])
return json.Unmarshal([]byte(jsonContent), target)
}
// If no code block found, return the original error
return err
}