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>
182 lines
4.5 KiB
Go
182 lines
4.5 KiB
Go
package pipes
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"nukumizu-backend/config"
|
|
"nukumizu-backend/internal/controller"
|
|
"nukumizu-backend/internal/netproxy"
|
|
"nukumizu-backend/internal/node"
|
|
"nukumizu-backend/internal/template"
|
|
"nukumizu-backend/postLog"
|
|
)
|
|
|
|
// WebhookController handles notifications via generic HTTP webhooks.
|
|
type WebhookController struct {
|
|
cfg config.WebhookConfig
|
|
httpClient *http.Client
|
|
}
|
|
|
|
// NewWebhookController creates a new Webhook controller.
|
|
func NewWebhookController(cfg config.WebhookConfig) *WebhookController {
|
|
return &WebhookController{
|
|
cfg: cfg,
|
|
httpClient: netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second),
|
|
}
|
|
}
|
|
|
|
// Name returns the controller name.
|
|
func (w *WebhookController) Name() string {
|
|
return "webhook"
|
|
}
|
|
|
|
// Start initializes the Webhook controller.
|
|
func (w *WebhookController) Start() error {
|
|
if !w.cfg.Enabled {
|
|
postLog.Info("Webhook controller is disabled")
|
|
return nil
|
|
}
|
|
postLog.Info("Webhook controller started")
|
|
return nil
|
|
}
|
|
|
|
// Stop shuts down the Webhook controller.
|
|
func (w *WebhookController) Stop() {
|
|
postLog.Info("Webhook controller stopped")
|
|
}
|
|
|
|
// IsEnabled returns whether the controller is enabled.
|
|
func (w *WebhookController) IsEnabled() bool {
|
|
return w.cfg.Enabled
|
|
}
|
|
|
|
// IsMarkdown returns whether the channel renders Markdown, per its markdown
|
|
// setting in config.json.
|
|
func (w *WebhookController) IsMarkdown() bool {
|
|
return w.cfg.Markdown
|
|
}
|
|
|
|
// SendStatusChange sends a status change notification via Webhook.
|
|
func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
|
|
if !w.cfg.Enabled {
|
|
return nil
|
|
}
|
|
|
|
cfg := config.Current()
|
|
params := template.BuildParamsFromStatusChange(change)
|
|
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, w.cfg.Markdown)
|
|
|
|
payload := map[string]interface{}{
|
|
"event": change.Event,
|
|
"serverName": change.Name,
|
|
"serverUUID": change.UUID,
|
|
"message": message,
|
|
"time": params.Time,
|
|
}
|
|
|
|
return w.send(payload)
|
|
}
|
|
|
|
// SendServerList sends the server list via Webhook.
|
|
func (w *WebhookController) SendServerList(onlineServers, offlineServers string) error {
|
|
if !w.cfg.Enabled {
|
|
return nil
|
|
}
|
|
|
|
cfg := config.Current()
|
|
params := template.BuildParamsFromServerList()
|
|
message := template.Render(cfg.ControllerMessage.ServerList, params, w.cfg.Markdown)
|
|
|
|
payload := map[string]interface{}{
|
|
"type": "serverList",
|
|
"onlineServers": params.OnlineServers,
|
|
"offlineServers": params.OfflineServers,
|
|
"message": message,
|
|
"time": params.Time,
|
|
}
|
|
|
|
return w.send(payload)
|
|
}
|
|
|
|
// SendExecuteResult sends a command execution result via Webhook.
|
|
func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, result string) error {
|
|
if !w.cfg.Enabled {
|
|
return nil
|
|
}
|
|
|
|
cfg := config.Current()
|
|
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
|
|
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, w.cfg.Markdown)
|
|
|
|
payload := map[string]interface{}{
|
|
"type": "executeResult",
|
|
"serverName": serverName,
|
|
"serverUUID": serverUUID,
|
|
"command": command,
|
|
"result": params.Result,
|
|
"message": message,
|
|
"time": params.Time,
|
|
}
|
|
|
|
return w.send(payload)
|
|
}
|
|
|
|
// SendAlert sends an alert submitted through the incoming webhook API to the
|
|
// configured URL.
|
|
func (w *WebhookController) SendAlert(alert controller.Alert) error {
|
|
if !w.cfg.Enabled {
|
|
return nil
|
|
}
|
|
|
|
payload := map[string]interface{}{
|
|
"type": "alert",
|
|
"subject": alert.Subject,
|
|
"source": alert.Source,
|
|
"content": alert.Content,
|
|
"message": alert.Render(w.cfg.Markdown),
|
|
"time": alert.Time,
|
|
}
|
|
|
|
return w.send(payload)
|
|
}
|
|
|
|
func (w *WebhookController) send(payload map[string]interface{}) error {
|
|
method := w.cfg.Method
|
|
if method == "" {
|
|
method = "POST"
|
|
}
|
|
|
|
bodyJSON, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal webhook payload: %w", err)
|
|
}
|
|
|
|
req, err := http.NewRequest(method, w.cfg.URL, bytes.NewReader(bodyJSON))
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create webhook request: %w", err)
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
for key, value := range w.cfg.Headers {
|
|
req.Header.Set(key, value)
|
|
}
|
|
|
|
resp, err := w.httpClient.Do(req)
|
|
if err != nil {
|
|
postLog.Warning("Failed to send webhook: " + err.Error())
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode >= 400 {
|
|
postLog.Warning(fmt.Sprintf("Webhook returned status %d", resp.StatusCode))
|
|
}
|
|
|
|
postLog.Debug("Webhook notification sent to " + w.cfg.URL)
|
|
return nil
|
|
}
|