Skip to content

Commit d6ace20

Browse files
committed
perf(config): optimize chroma style loading for better concurrency
- replace `sync.Mutex` with `sync.RWMutex` to allow concurrent reads - implement double-checked locking pattern in `GetChromaStyle` - move heavy i/o operations outside of critical sections - minimize lock duration by protecting only registry access - add race condition prevention with second existence check
1 parent f82ee62 commit d6ace20

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

internal/config/style.go

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const (
2323
chromaStyleTheme = "kyma"
2424
)
2525

26-
var chromaMutex = sync.Mutex{}
26+
var chromaMutex = sync.RWMutex{}
2727

2828
type Properties struct {
2929
Title string `yaml:"title"`
@@ -317,17 +317,25 @@ func ChromaStyle(style ansi.StylePrimitive) string {
317317
func GetChromaStyle(themeName string) *chroma.Style {
318318
customThemeName := chromaStyleTheme + "-" + themeName
319319

320-
chromaMutex.Lock()
321-
defer chromaMutex.Unlock()
320+
switch themeName {
321+
case "dracula":
322+
return chromaStyles.Get("dracula")
323+
case "tokyo-night", "tokyonight":
324+
return chromaStyles.Get("tokyo-night")
325+
}
322326

327+
chromaMutex.RLock()
323328
if chromaStyle, ok := chromaStyles.Registry[customThemeName]; ok {
329+
chromaMutex.RUnlock()
324330
return chromaStyle
325331
}
332+
chromaMutex.RUnlock()
326333

327334
styleConfig := getTheme(themeName)
328335
style := styleConfig.Style
336+
329337
if style.CodeBlock.Chroma != nil {
330-
style := chroma.MustNewStyle(customThemeName,
338+
newStyle := chroma.MustNewStyle(customThemeName,
331339
chroma.StyleEntries{
332340
chroma.Text: ChromaStyle(style.CodeBlock.Chroma.Text),
333341
chroma.Error: ChromaStyle(style.CodeBlock.Chroma.Error),
@@ -361,20 +369,17 @@ func GetChromaStyle(themeName string) *chroma.Style {
361369
chroma.GenericSubheading: ChromaStyle(style.CodeBlock.Chroma.GenericSubheading),
362370
chroma.Background: ChromaStyle(style.CodeBlock.Chroma.Background),
363371
})
364-
chromaStyles.Register(style)
365-
return style
366-
}
367372

368-
switch themeName {
369-
case "dracula":
370-
return chromaStyles.Get("dracula")
371-
case "dark":
372-
return chromaStyles.Get("github-dark")
373-
case "light":
374-
return chromaStyles.Get("github")
375-
case "tokyo-night", "tokyonight":
376-
return chromaStyles.Get("tokyo-night")
377-
default:
378-
return chromaStyles.Fallback
373+
chromaMutex.Lock()
374+
375+
if existingStyle, ok := chromaStyles.Registry[customThemeName]; ok {
376+
chromaMutex.Unlock()
377+
return existingStyle
378+
}
379+
chromaStyles.Register(newStyle)
380+
chromaMutex.Unlock()
381+
return newStyle
379382
}
383+
384+
return chromaStyles.Fallback
380385
}

0 commit comments

Comments
 (0)