refactor(config): publish config singletons through atomic pointers

The three configuration singletons (C_globalConfig, C_botUserConfig,
C_botNodeConfig) were plain variables: LoadGlobalConfig and friends assigned
them from the goroutine handling a settings update, while bot pipes, the node
tracker and the HTTP handlers read them from their own goroutines. That is an
unsynchronized read of a concurrently written variable — a data race the race
detector reports, and one that already existed before any hot-reload work
because /api/webhook/add reloads the configuration while the bots run.

Replace them with atomic.Pointer values behind Current(), BotUsers() and
BotNodes(). Each reload builds a fresh value and publishes it atomically, so a
reader either sees the previous configuration or the new one, never a partial
one. Callers read through the accessor on every use instead of caching it.

Two spots that read several fields of one guard now snapshot once per call, so
a reload cannot split a combined check mid-flight:
- qq_napcat.handleNapcatEvent, which evaluates the debug guards per event
- the komari task-echo guard, now behind taskEchoEnabled()

The NapCat HTTP methods keep logging on showNapcatAction alone (without
requiring debugMode), matching their existing behaviour; that inconsistency
with the WebSocket path is preserved, not introduced, and is called out in
actionLogEnabled.

Also adds TestConcurrentReloadAndRead, which drives every accessor from four
reader goroutines while two writers reload the configuration, and sanitises the
member IDs used as test fixtures in config/settings_test.go.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-09-28 22:47:37 +08:00
co-authored by Claude Code
parent 2d5cf39151
commit cb2df5076d
16 changed files with 314 additions and 77 deletions
+2 -2
View File
@@ -144,7 +144,7 @@ func (m *Manager) ShowBotInitMessage() {
m.mu.RLock()
defer m.mu.RUnlock()
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildBotInitializationMsgParams()
for _, ctrl := range m.controllers {
@@ -176,7 +176,7 @@ func (m *Manager) ShowBotServerList() {
m.mu.RLock()
defer m.mu.RUnlock()
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
for _, ctrl := range m.controllers {
+3 -3
View File
@@ -71,7 +71,7 @@ func (e *EmailController) SendStatusChange(change node.StatusChange) error {
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
body := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, e.cfg.Markdown)
@@ -85,7 +85,7 @@ func (e *EmailController) SendServerList(onlineServers, offlineServers string) e
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
body := template.Render(cfg.ControllerMessage.ServerList, params, e.cfg.Markdown)
@@ -98,7 +98,7 @@ func (e *EmailController) SendExecuteResult(serverName, serverUUID, command, res
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
body := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, e.cfg.Markdown)
+3 -3
View File
@@ -65,7 +65,7 @@ func (n *NtfyController) SendStatusChange(change node.StatusChange) error {
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, n.cfg.Markdown)
@@ -79,7 +79,7 @@ func (n *NtfyController) SendServerList(onlineServers, offlineServers string) er
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params, n.cfg.Markdown)
@@ -92,7 +92,7 @@ func (n *NtfyController) SendExecuteResult(serverName, serverUUID, command, resu
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, n.cfg.Markdown)
+14 -5
View File
@@ -17,6 +17,15 @@ import (
"nukumizu-backend/postLog"
)
// actionLogEnabled reports whether the NapCat HTTP API methods echo each action
// they send, per the showNapcatAction toggle. Unlike the WebSocket message path
// in qq.go it deliberately does not also require debugMode: these methods have
// always logged on this toggle alone, and preserving that is intentional.
func actionLogEnabled() bool {
cfg := config.Current()
return cfg != nil && cfg.Debug.ShowNapcatAction
}
// APIResponse mirrors NapCat's HTTP API response envelope.
type APIResponse struct {
Status string `json:"status"`
@@ -155,7 +164,7 @@ func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bo
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if config.C_globalConfig.Debug.ShowNapcatAction {
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] SendMsg -> %s (%s): %s", endpoint, targetType, message))
}
@@ -176,7 +185,7 @@ func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if config.C_globalConfig.Debug.ShowNapcatAction {
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] RecallMsg -> /delete_msg: %d", msgID))
}
@@ -190,7 +199,7 @@ func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
// GetGroupList retrieves the list of joined groups from NapCat.
func (c *Client) GetGroupList() (*APIResponse, error) {
if config.C_globalConfig.Debug.ShowNapcatAction {
if actionLogEnabled() {
postLog.Debug("[Napcat] GetGroupList -> /get_group_list")
}
@@ -211,7 +220,7 @@ func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if config.C_globalConfig.Debug.ShowNapcatAction {
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] GetGroupInfo -> /get_group_info: %d", groupID))
}
@@ -225,7 +234,7 @@ func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
// GetFriendsList retrieves the friends list from NapCat.
func (c *Client) GetFriendsList() (*APIResponse, error) {
if config.C_globalConfig.Debug.ShowNapcatAction {
if actionLogEnabled() {
postLog.Debug("[Napcat] GetFriendsList -> /get_friend_list")
}
+26 -15
View File
@@ -100,24 +100,34 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
return
}
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowNapcatMsg {
// The configuration is read once per event: the debug guards below are
// evaluated several times, and taking them all from one version keeps a
// concurrent reload from splitting them mid-event.
cfg := config.Current()
if cfg == nil {
return
}
debugMode := cfg.System.DebugMode
showAction := debugMode && cfg.Debug.ShowNapcatAction
if debugMode && cfg.Debug.ShowNapcatMsg {
postLog.Debug("Napcat WS event received: " + string(raw))
}
// Only handle message events; ignore notice/request/meta_event.
if ev.PostType != "message" {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowNapcatAction {
if showAction {
postLog.Debug("Ignoring Napcat WS event: " + string(raw))
}
return
}
// Ignore messages the bot itself sent (echo prevention).
if q.isSelfMessage(ev) && !config.C_globalConfig.System.DebugMode {
if q.isSelfMessage(ev) && !debugMode {
return
}
if q.isSelfMessage(ev) && config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.NapcatIgnoreSelfMsg {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowNapcatAction {
if q.isSelfMessage(ev) && debugMode && cfg.Debug.NapcatIgnoreSelfMsg {
if showAction {
postLog.Debug("Ignoring Napcat WS self message: " + string(raw))
}
return
@@ -138,7 +148,7 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
response := q.processCommand(cmd)
if response == "" {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowNapcatAction {
if showAction {
postLog.Debug("Napcat WS command discarded: " + string(raw))
}
return
@@ -160,6 +170,7 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
// complete command to the unified processor. It returns the response text to
// reply with; an empty response means the message was discarded.
func (q *QQController) processCommand(cmd controller.Command) string {
cfg := config.Current()
text := cmd.RawText
// In "at" listen mode, require an @mention of the bot and strip it before
@@ -168,7 +179,7 @@ func (q *QQController) processCommand(cmd controller.Command) string {
if q.cfg.ListenMethod == "at" {
atMention := fmt.Sprintf("[CQ:at,qq=%d]", q.cfg.BotQQID)
if !strings.Contains(text, atMention) {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowNapcatAction {
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowNapcatAction {
postLog.Debug("Napcat WS message ignored (no @mention): " + text)
}
return "" // Not mentioned, ignore.
@@ -190,7 +201,7 @@ func (q *QQController) processCommand(cmd controller.Command) string {
// Hand the complete command to the unified processor, which checks group
// vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, q.trustedGroupIDs(), q.adminIDs(), q.cfg.ListenMethod)
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowTriggerCmdEcho {
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowTriggerCmdEcho {
postLog.Debug(fmt.Sprintf("[qq_napcat] triggered command: \"/%s\" with args: \"%s\" from chatID: %d and senderID: %d", parsed.Command, strings.Join(parsed.Args, ", "), cmd.ChatID, cmd.SenderID))
}
if err != nil {
@@ -213,7 +224,7 @@ func (q *QQController) isSelfMessage(ev oneBotEvent) bool {
// adminIDs returns the QQ admin IDs from bot_user_config.json.
func (q *QQController) adminIDs() []string {
if c := config.C_botUserConfig; c != nil {
if c := config.BotUsers(); c != nil {
return c.QQ.Admins.IDs()
}
return nil
@@ -221,7 +232,7 @@ func (q *QQController) adminIDs() []string {
// trustedGroupIDs returns the QQ trusted group IDs from bot_user_config.json.
func (q *QQController) trustedGroupIDs() []string {
if c := config.C_botUserConfig; c != nil {
if c := config.BotUsers(); c != nil {
return c.QQ.TrustedGroups.IDs()
}
return nil
@@ -237,7 +248,7 @@ func (q *QQController) SendMessage(message controller.Message) error {
}
// Only notify trusted groups and admins whose options allow this message type.
if uc := config.C_botUserConfig; uc != nil {
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.QQ.TrustedGroups {
if !controller.MemberReceives(opts, message.Type) {
continue
@@ -260,12 +271,12 @@ func (q *QQController) SendStatusChange(change node.StatusChange) error {
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, q.cfg.Markdown)
// Only notify trusted groups and admins whose event_status_notify is true.
if uc := config.C_botUserConfig; uc != nil {
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.QQ.TrustedGroups {
if !opts.EventStatusNotify {
continue
@@ -289,7 +300,7 @@ func (q *QQController) SendServerList(onlineServers, offlineServers string) erro
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params, q.cfg.Markdown)
@@ -305,7 +316,7 @@ func (q *QQController) SendExecuteResult(serverName, serverUUID, command, result
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, q.cfg.Markdown)
@@ -148,7 +148,7 @@ func (t *TelegramController) handleUpdate(_ context.Context, _ *bot.Bot, update
}
msg := update.Message
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowTelegramMsg {
if cfg := config.Current(); cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowTelegramMsg {
raw, _ := json.Marshal(update)
postLog.Debug("Telegram update received: " + string(raw))
}
@@ -232,7 +232,7 @@ func (t *TelegramController) processCommand(cmd controller.Command) string {
// Hand the complete command to the unified processor, which checks group
// vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, t.trustedGroupIDs(), t.resolvedAdminList(), t.cfg.ListenMethod)
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowTriggerCmdEcho {
if cfg := config.Current(); cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowTriggerCmdEcho {
postLog.Debug(fmt.Sprintf("[telegram] triggered command: \"/%s\" with args: \"%s\" from chatID: %d and senderID: %d", parsed.Command, strings.Join(parsed.Args, ", "), cmd.ChatID, cmd.SenderID))
}
if err != nil {
@@ -252,7 +252,7 @@ func (t *TelegramController) SendMessage(message controller.Message) error {
}
// Only notify trusted groups and admins whose options allow this message type.
if uc := config.C_botUserConfig; uc != nil {
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.Telegram.TrustedGroups {
if !controller.MemberReceives(opts, message.Type) {
continue
@@ -275,12 +275,12 @@ func (t *TelegramController) SendStatusChange(change node.StatusChange) error {
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, t.cfg.Markdown)
// Only notify trusted groups and admins whose event_status_notify is true.
if uc := config.C_botUserConfig; uc != nil {
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.Telegram.TrustedGroups {
if !opts.EventStatusNotify {
continue
@@ -303,7 +303,7 @@ func (t *TelegramController) SendServerList(onlineServers, offlineServers string
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params, t.cfg.Markdown)
@@ -317,7 +317,7 @@ func (t *TelegramController) SendExecuteResult(serverName, serverUUID, command,
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, t.cfg.Markdown)
@@ -395,7 +395,7 @@ func (t *TelegramController) resolveUsername(username string) (int64, bool) {
// adminIDs returns the Telegram admin entries (numeric user ID or @username)
// from bot_user_config.json.
func (t *TelegramController) adminIDs() []string {
if c := config.C_botUserConfig; c != nil {
if c := config.BotUsers(); c != nil {
return c.Telegram.Admins.IDs()
}
return nil
@@ -403,7 +403,7 @@ func (t *TelegramController) adminIDs() []string {
// trustedGroupIDs returns the Telegram trusted group IDs from bot_user_config.json.
func (t *TelegramController) trustedGroupIDs() []string {
if c := config.C_botUserConfig; c != nil {
if c := config.BotUsers(); c != nil {
return c.Telegram.TrustedGroups.IDs()
}
return nil
+3 -3
View File
@@ -66,7 +66,7 @@ func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, w.cfg.Markdown)
@@ -87,7 +87,7 @@ func (w *WebhookController) SendServerList(onlineServers, offlineServers string)
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params, w.cfg.Markdown)
@@ -108,7 +108,7 @@ func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, r
return nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, w.cfg.Markdown)
+4 -4
View File
@@ -22,13 +22,13 @@ func commandMarkdown(cmd Command) bool {
}
func handleHelp(cmd Command) (string, error) {
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildBotInitializationMsgParams()
return template.Render(cfg.ControllerMessage.BotHelp, params, commandMarkdown(cmd)), nil
}
func handleList(cmd Command) (string, error) {
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromServerList()
return template.Render(cfg.ControllerMessage.ServerList, params, commandMarkdown(cmd)), nil
}
@@ -139,7 +139,7 @@ func handleRun(cmd Command) (string, error) {
return fmt.Sprintf("Error getting results: %v", err), nil
}
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildParamsFromExecResult(uuidArg, uuidArg, command, formatTaskResults(results))
return template.Render(cfg.ControllerMessage.ServerExecuteResult, params, commandMarkdown(cmd)), nil
}
@@ -189,7 +189,7 @@ func handleInfo(cmd Command) (string, error) {
}
func telegram_handleStart(cmd Command) (string, error) {
cfg := config.C_globalConfig
cfg := config.Current()
params := template.BuildBotInitializationMsgParams()
return template.Render(cfg.ControllerMessage.Tg_BotStart, params, commandMarkdown(cmd)), nil
}
+12 -4
View File
@@ -18,6 +18,14 @@ import (
"nukumizu-backend/postLog"
)
// taskEchoEnabled reports whether Komari task progress should be echoed to the
// log: debug mode plus the showKomariTaskEcho toggle. The configuration is read
// once per call so both flags come from the same reload.
func taskEchoEnabled() bool {
cfg := config.Current()
return cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowKomariTaskEcho
}
// NodeInfo represents a single node as returned by Komari's
// common:getNodes RPC2 method.
type NodeInfo struct {
@@ -146,7 +154,7 @@ func (c *Client) Login(username, password string) error {
var kr KomariResponse
if err := json.NewDecoder(resp.Body).Decode(&kr); err != nil {
if config.C_globalConfig.System.DebugMode {
if config.IsDebugMode() {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to parse komari login response: %w.\nResponse: %s", err, respBody)
}
@@ -332,7 +340,7 @@ func (c *Client) ExecTask(uuids []string, command string) (string, error) {
return "", fmt.Errorf("failed to parse komari task exec data: %w", err)
}
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowKomariTaskEcho {
if taskEchoEnabled() {
postLog.Debug(fmt.Sprintf("Created Komari task %s for %d clients", result.TaskID, len(uuids)))
}
return result.TaskID, nil
@@ -375,7 +383,7 @@ func (c *Client) GetTaskResult(taskID string) ([]TaskResult, bool, error) {
// PollTaskResult polls for task results every 1 second until all results are
// available or 60 seconds have elapsed.
func (c *Client) PollTaskResult(taskID string) ([]TaskResult, error) {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowKomariTaskEcho {
if taskEchoEnabled() {
postLog.Debug(fmt.Sprintf("Polling for Komari task %s results...", taskID))
}
@@ -393,7 +401,7 @@ func (c *Client) PollTaskResult(taskID string) ([]TaskResult, error) {
return nil, err
}
if done {
if config.C_globalConfig.System.DebugMode && config.C_globalConfig.Debug.ShowKomariTaskEcho {
if taskEchoEnabled() {
postLog.Info(fmt.Sprintf("Task %s completed with %d results", taskID, len(results)))
}
return results, nil
+4 -1
View File
@@ -409,7 +409,10 @@ func GetWSClient() *WSClient {
// LoginAndStart performs the Komari login and returns an error if it fails.
func LoginAndStart() error {
cfg := config.C_globalConfig
cfg := config.Current()
if cfg == nil {
return fmt.Errorf("configuration not loaded")
}
client := GetClient()
if client == nil {
return fmt.Errorf("komari client not initialized")
+5 -1
View File
@@ -20,7 +20,11 @@ import (
// proxyURL returns the system-wide network proxy URL, or nil when none is
// configured. A missing scheme is normalized to http:// for convenience.
func proxyURL() *url.URL {
raw := config.C_globalConfig.System.NetworkProxy
cfg := config.Current()
if cfg == nil {
return nil
}
raw := cfg.System.NetworkProxy
if raw == "" {
return nil
}