MCPcopy
hub / github.com/fish2018/pansou / AsyncSearch

Method AsyncSearch

plugin/plugin.go:528–782  ·  view source on GitHub ↗

============================================================ 第八部分:异步搜索核心逻辑 ============================================================ AsyncSearch 异步搜索基础方法

(
	keyword string,
	searchFunc func(*http.Client, string, map[string]interface{}) ([]model.SearchResult, error),
	mainCacheKey string,
	ext map[string]interface{},
)

Source from the content-addressed store, hash-verified

526
527// AsyncSearch 异步搜索基础方法
528func (p *BaseAsyncPlugin) AsyncSearch(
529 keyword string,
530 searchFunc func(*http.Client, string, map[string]interface{}) ([]model.SearchResult, error),
531 mainCacheKey string,
532 ext map[string]interface{},
533) ([]model.SearchResult, error) {
534 // 确保ext不为nil
535 if ext == nil {
536 ext = make(map[string]interface{})
537 }
538
539 now := time.Now()
540
541 // 修改缓存键,确保包含插件名称
542 pluginSpecificCacheKey := fmt.Sprintf("%s:%s", p.name, keyword)
543
544 // 检查缓存
545 if cachedItems, ok := apiResponseCache.Load(pluginSpecificCacheKey); ok {
546 cachedResult := cachedItems.(cachedResponse)
547
548 // 缓存完全有效(未过期且完整)
549 if time.Since(cachedResult.Timestamp) < p.cacheTTL && cachedResult.Complete {
550 recordCacheHit()
551 recordCacheAccess(pluginSpecificCacheKey)
552
553 // 如果缓存接近过期(已用时间超过TTL的80%),在后台刷新缓存
554 if time.Since(cachedResult.Timestamp) > (p.cacheTTL * 4 / 5) {
555 go p.refreshCacheInBackground(keyword, pluginSpecificCacheKey, searchFunc, cachedResult, mainCacheKey, ext)
556 }
557
558 return cachedResult.Results, nil
559 }
560
561 // 缓存已过期但有结果,启动后台刷新,同时返回旧结果
562 if len(cachedResult.Results) > 0 {
563 recordCacheHit()
564 recordCacheAccess(pluginSpecificCacheKey)
565
566 // 标记为部分过期
567 if time.Since(cachedResult.Timestamp) >= p.cacheTTL {
568 // 在后台刷新缓存
569 go p.refreshCacheInBackground(keyword, pluginSpecificCacheKey, searchFunc, cachedResult, mainCacheKey, ext)
570
571 // 日志记录
572 fmt.Printf("[%s] 缓存已过期,后台刷新中: %s (已过期: %v)\n",
573 p.name, pluginSpecificCacheKey, time.Since(cachedResult.Timestamp))
574 }
575
576 return cachedResult.Results, nil
577 }
578 }
579
580 recordCacheMiss()
581
582 // 创建通道
583 resultChan := make(chan []model.SearchResult, 1)
584 errorChan := make(chan error, 1)
585 doneChan := make(chan struct{})

Callers

nothing calls this directly

Calls 8

recordCacheHitFunction · 0.85
recordCacheAccessFunction · 0.85
recordCacheMissFunction · 0.85
acquireWorkerSlotFunction · 0.85
releaseWorkerSlotFunction · 0.85
recordAsyncCompletionFunction · 0.85

Tested by

no test coverage detected