Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Synchronize emoji and RHY cache updates https://github.com/siyuan-note/siyuan/issues/20198

Danielab2699459db0
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 52d99985ec..1ecf32b66f 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -2522,7 +2522,7 @@ func getAssetLinkDestsByNode(node *ast.Node, includeServePath bool, normalize ..
func emojisInTree(tree *parse.Tree) (ret []string) {
if icon := tree.Root.IALAttr("icon"); "" != icon {
- if !strings.Contains(icon, "://") && !strings.HasPrefix(icon, "api/icon/") && !util.NativeEmojiChars[icon] {
+ if !strings.Contains(icon, "://") && !strings.HasPrefix(icon, "api/icon/") && !util.IsNativeEmoji(icon) {
ret = append(ret, "/emojis/"+icon)
}
}
diff --git a/kernel/util/rhy.go b/kernel/util/rhy.go
index 73fbe786f7..8db20d1572 100644
--- a/kernel/util/rhy.go
+++ b/kernel/util/rhy.go
@@ -32,7 +32,7 @@ var (
cachedRhyResult = map[string]any{}
rhyResultCacheTime int64
- rhyResultLock = sync.Mutex{}
+ rhyResultLock = sync.RWMutex{}
rhyResultFlight singleflight.Group
rhyBazaarHash string
@@ -51,17 +51,22 @@ func RefreshRhyResultJob() {
}
func GetRhyResult(ctx context.Context, force bool) (map[string]any, error) {
+ cacheDuration := RhyCacheDuration
if ContainerDocker == Container {
- RhyCacheDuration = int64(3600 * 24)
+ cacheDuration = int64(3600 * 24)
}
- if RhyCacheDuration >= time.Now().Unix()-rhyResultCacheTime && !force && 0 < len(cachedRhyResult) {
- return cachedRhyResult, nil
+ rhyResultLock.RLock()
+ cached := cachedRhyResult
+ valid := cacheDuration >= time.Now().Unix()-rhyResultCacheTime && len(cached) > 0
+ rhyResultLock.RUnlock()
+ if !force && valid {
+ return cached, nil
}
// 并发调用只执行一次实际请求
v, err, _ := rhyResultFlight.Do("rhyResult", func() (any, error) {
- return getRhyResult0(ctx)
+ return getRhyResult0(ctx, GetCloudServer())
})
if err != nil {
return nil, err
@@ -71,12 +76,11 @@ func GetRhyResult(ctx context.Context, force bool) (map[string]any, error) {
return ret, nil
}
-func getRhyResult0(ctx context.Context) (map[string]any, error) {
- rhyResultLock.Lock()
- defer rhyResultLock.Unlock()
-
+func getRhyResult0(ctx context.Context, serverURL string) (map[string]any, error) {
+ // 响应使用独立对象解析,已发布的缓存只读,刷新不会改写调用方正在使用的结果。
+ var result map[string]any
request := httpclient.NewCloudRequest30s()
- resp, err := request.SetContext(ctx).SetSuccessResult(&cachedRhyResult).Get(GetCloudServer() + "/apis/siyuan/version?ver=" + Ver)
+ resp, err := request.SetContext(ctx).SetSuccessResult(&result).Get(serverURL + "/apis/siyuan/version?ver=" + Ver)
if err != nil {
logging.LogErrorf("get version info failed: %s", err)
return nil, err
@@ -85,8 +89,11 @@ func getRhyResult0(ctx context.Context) (map[string]any, error) {
logging.LogErrorf("get rhy result failed: %d", resp.StatusCode)
return nil, fmt.Errorf("get rhy result failed: %d", resp.StatusCode)
}
+ rhyResultLock.Lock()
+ cachedRhyResult = result
rhyResultCacheTime = time.Now().Unix()
- return cachedRhyResult, nil
+ rhyResultLock.Unlock()
+ return result, nil
}
func syncRhyBazaarHashFromResult(m map[string]any) {
diff --git a/kernel/util/rune.go b/kernel/util/rune.go
index 70ccf9eb4d..e0fb903dfa 100644
--- a/kernel/util/rune.go
+++ b/kernel/util/rune.go
@@ -21,6 +21,7 @@ import (
"path/filepath"
"regexp"
"strings"
+ "sync"
"unicode"
"github.com/88250/gulu"
@@ -85,7 +86,16 @@ func RemoveInvalidRetainCtrl(text string) (ret string) {
return
}
-var NativeEmojiChars = map[string]bool{}
+var (
+ nativeEmojiChars = map[string]bool{}
+ nativeEmojiCharsLock sync.RWMutex
+)
+
+func IsNativeEmoji(value string) bool {
+ nativeEmojiCharsLock.RLock()
+ defer nativeEmojiCharsLock.RUnlock()
+ return nativeEmojiChars[value]
+}
func InitEmojiChars() {
builtConfPath := filepath.Join(AppearancePath, "emojis", "conf.json")
@@ -101,12 +111,16 @@ func InitEmojiChars() {
return
}
+ chars := map[string]bool{}
for _, emoji := range conf {
items := emoji["items"].([]any)
for _, item := range items {
e := item.(map[string]any)
- NativeEmojiChars[e["unicode"].(string)] = true
+ chars[e["unicode"].(string)] = true
}
}
+ nativeEmojiCharsLock.Lock()
+ nativeEmojiChars = chars
+ nativeEmojiCharsLock.Unlock()
return
}
diff --git a/kernel/util/shared_cache_test.go b/kernel/util/shared_cache_test.go
new file mode 100644
index 0000000000..4c3d00b0cd
--- /dev/null
+++ b/kernel/util/shared_cache_test.go
@@ -0,0 +1,149 @@
+package util
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestNativeEmojiCacheReplacementAndConcurrentReads(t *testing.T) {
+ oldAppearance := AppearancePath
+ nativeEmojiCharsLock.RLock()
+ oldChars := nativeEmojiChars
+ nativeEmojiCharsLock.RUnlock()
+ AppearancePath = t.TempDir()
+ t.Cleanup(func() {
+ AppearancePath = oldAppearance
+ nativeEmojiCharsLock.Lock()
+ nativeEmojiChars = oldChars
+ nativeEmojiCharsLock.Unlock()
+ })
+ directory := filepath.Join(AppearancePath, "emojis")
+ if err := os.MkdirAll(directory, 0755); err != nil {
+ t.Fatal(err)
+ }
+ write := func(value string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(directory, "conf.json"), []byte(value), 0644); err != nil {
+ t.Fatal(err)
+ }
+ InitEmojiChars()
+ }
+ write(`[{"items":[{"unicode":"old"}]}]`)
+ if !IsNativeEmoji("old") {
+ t.Fatal("emoji list was not loaded")
+ }
+ write(`[{"items":[{"unicode":"new"}]}]`)
+ if IsNativeEmoji("old") || !IsNativeEmoji("new") {
+ t.Fatal("emoji refresh retained removed entries")
+ }
+ write(`invalid`)
+ if !IsNativeEmoji("new") {
+ t.Fatal("failed refresh discarded the last valid emoji list")
+ }
+ write(`[{"items":[{"unicode":"new"}]}]`)
+ var group sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ group.Go(func() {
+ for j := 0; j < 50; j++ {
+ InitEmojiChars()
+ if !IsNativeEmoji("new") || IsNativeEmoji("old") {
+ t.Error("concurrent refresh changed emoji membership")
+ return
+ }
+ }
+ })
+ }
+ group.Wait()
+}
+
+func TestRhyCacheSnapshotsAndConcurrentRefresh(t *testing.T) {
+ rhyResultLock.Lock()
+ oldResult, oldTime := cachedRhyResult, rhyResultCacheTime
+ rhyResultLock.Unlock()
+ rhyBazaarHashLock.RLock()
+ oldHash := rhyBazaarHash
+ rhyBazaarHashLock.RUnlock()
+ oldContainer := Container
+ oldDuration := RhyCacheDuration
+ Container = ContainerDocker
+ t.Cleanup(func() {
+ Container = oldContainer
+ rhyResultLock.Lock()
+ cachedRhyResult, rhyResultCacheTime = oldResult, oldTime
+ rhyResultLock.Unlock()
+ rhyBazaarHashLock.Lock()
+ rhyBazaarHash = oldHash
+ rhyBazaarHashLock.Unlock()
+ })
+ var count atomic.Int32
+ var fail atomic.Bool
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if fail.Load() {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if n := count.Add(1); n == 1 {
+ fmt.Fprint(w, `{"bazaar":"hash-1","removed":true,"checksums":{"file":"first"}}`)
+ } else {
+ fmt.Fprintf(w, `{"bazaar":"hash-%d","checksums":{"file":"updated"}}`, n)
+ }
+ }))
+ defer server.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ first, err := getRhyResult0(ctx, server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := getRhyResult0(ctx, server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first["bazaar"] != "hash-1" || first["checksums"].(map[string]any)["file"] != "first" || second["removed"] != nil {
+ t.Fatal("cache refresh modified an existing snapshot or retained removed fields")
+ }
+ fail.Store(true)
+ if _, err = getRhyResult0(ctx, server.URL); err == nil {
+ t.Fatal("failed refresh was accepted")
+ }
+ cached, err := GetRhyResult(ctx, false)
+ if err != nil || cached["bazaar"] != second["bazaar"] {
+ t.Fatal("failed refresh replaced the valid cache")
+ }
+ fail.Store(false)
+ var group sync.WaitGroup
+ group.Go(func() {
+ for i := 0; i < 25; i++ {
+ if _, err := getRhyResult0(ctx, server.URL); err != nil {
+ t.Error(err)
+ return
+ }
+ }
+ })
+ for i := 0; i < 8; i++ {
+ group.Go(func() {
+ for j := 0; j < 100; j++ {
+ result, err := GetRhyResult(ctx, false)
+ if err != nil || !strings.HasPrefix(result["bazaar"].(string), "hash-") {
+ t.Errorf("invalid cached result: %#v err=%v", result, err)
+ return
+ }
+ syncRhyBazaarHashFromResult(result)
+ }
+ })
+ }
+ group.Wait()
+ if first["bazaar"] != "hash-1" || RhyCacheDuration != oldDuration {
+ t.Fatal("concurrent refresh modified a snapshot or global duration")
+ }
+}