refactor(controller): apply controller settings by rebuilding the channel set
Giving each controller a Reload method worked for the notification pipes, which only hold values, but not for the two bot channels: the NapCat client is stopped through a sync.Once and the Telegram polling context is created with the controller, so neither can be re-pointed once running. It also meant five bespoke implementations of the same idea. Replace the whole set instead. Manager.ReplaceAll swaps in a freshly built set under the registry lock, stops the outgoing controllers outside it, and starts the incoming ones off the calling goroutine so a slow handshake does not hold the settings request open. ReplaceAll is now the only way controllers are installed: Register is gone, because a lone registration would slip a controller in without recording the settings it was built from, which is what NeedsRebuild compares against. The rebuild runs from the reload hook and only fires when the controllerMethod section actually changed, so saving a message template or a webhook endpoint leaves the channels alone. NeedsRebuild compares the whole section by value, and a test pins that reloading a file reproduces it exactly — a default applied inconsistently would make every save look like a controller change and tear down every channel. With controllers immutable after construction and replaced wholesale, the atomic pointers and Reload methods have no writers left, so they are gone and the pipes return to plain fields. notifyReload now serializes hook execution for the same reason: a hook mutates process-wide state, and two overlapping settings updates would otherwise each decide to rebuild from their own view of what was applied. Kept from that work: applyEmailProxy restores gomail's default dialer when networkUseProxy is turned off. The old constructor only ever installed the proxy dialer, so switching the flag back left SMTP tunnelled through a proxy with no way to undo it short of a restart. Documents the resulting behaviour in the README under "What applies without a restart".
This commit is contained in:
@@ -5,8 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"nukumizu-backend/config"
|
||||
@@ -19,32 +17,21 @@ import (
|
||||
|
||||
// WebhookController handles notifications via generic HTTP webhooks.
|
||||
//
|
||||
// Both fields are held behind atomic pointers rather than in plain fields:
|
||||
// Reload replaces them on the settings-update goroutine while the send methods
|
||||
// read them on the status-change and incoming-webhook goroutines.
|
||||
// cfg and httpClient are written once, by the constructor, and never again: a
|
||||
// controller that needs different settings is replaced wholesale by the manager
|
||||
// rather than reconfigured in place, so the send methods can read them without
|
||||
// locking.
|
||||
type WebhookController struct {
|
||||
cfg atomic.Pointer[config.WebhookConfig]
|
||||
httpClient atomic.Pointer[http.Client]
|
||||
cfg config.WebhookConfig
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// NewWebhookController creates a new Webhook controller.
|
||||
func NewWebhookController(cfg config.WebhookConfig) *WebhookController {
|
||||
w := &WebhookController{}
|
||||
w.cfg.Store(&cfg)
|
||||
w.httpClient.Store(netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second))
|
||||
return w
|
||||
}
|
||||
|
||||
// settings returns the configuration currently in effect. The value it points
|
||||
// at is never mutated after being stored, so a caller can hold the pointer for
|
||||
// one whole send without a concurrent Reload disturbing it.
|
||||
func (w *WebhookController) settings() *config.WebhookConfig {
|
||||
return w.cfg.Load()
|
||||
}
|
||||
|
||||
// client returns the HTTP client built for the current proxy setting.
|
||||
func (w *WebhookController) client() *http.Client {
|
||||
return w.httpClient.Load()
|
||||
return &WebhookController{
|
||||
cfg: cfg,
|
||||
httpClient: netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
// Name returns the controller name.
|
||||
@@ -54,7 +41,7 @@ func (w *WebhookController) Name() string {
|
||||
|
||||
// Start initializes the Webhook controller.
|
||||
func (w *WebhookController) Start() error {
|
||||
if !w.settings().Enabled {
|
||||
if !w.cfg.Enabled {
|
||||
postLog.Info("Webhook controller is disabled")
|
||||
return nil
|
||||
}
|
||||
@@ -67,51 +54,26 @@ func (w *WebhookController) Stop() {
|
||||
postLog.Info("Webhook controller stopped")
|
||||
}
|
||||
|
||||
// Reload applies the current configuration. Everything the sender reads is
|
||||
// taken from the settings at send time, so only a change to the proxy flag
|
||||
// needs more than the swap: that one is baked into the HTTP client's transport
|
||||
// when the client is built.
|
||||
func (w *WebhookController) Reload() {
|
||||
global := config.Current()
|
||||
if global == nil {
|
||||
return
|
||||
}
|
||||
|
||||
current := w.settings()
|
||||
updated := global.ControllerMethod.Webhook
|
||||
// WebhookConfig carries a header map, so it is not comparable with ==.
|
||||
if reflect.DeepEqual(*current, updated) {
|
||||
return
|
||||
}
|
||||
|
||||
if current.NetworkUseProxy != updated.NetworkUseProxy {
|
||||
w.httpClient.Store(netproxy.HTTPClient(updated.NetworkUseProxy, 10*time.Second))
|
||||
}
|
||||
w.cfg.Store(&updated)
|
||||
postLog.Debug("Webhook controller reloaded")
|
||||
}
|
||||
|
||||
// IsEnabled returns whether the controller is enabled.
|
||||
func (w *WebhookController) IsEnabled() bool {
|
||||
return w.settings().Enabled
|
||||
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.settings().Markdown
|
||||
return w.cfg.Markdown
|
||||
}
|
||||
|
||||
// SendStatusChange sends a status change notification via Webhook.
|
||||
func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
if !w.cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromStatusChange(change)
|
||||
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, s.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, w.cfg.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"event": change.Event,
|
||||
@@ -126,14 +88,13 @@ func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
|
||||
|
||||
// SendServerList sends the server list via Webhook.
|
||||
func (w *WebhookController) SendServerList(onlineServers, offlineServers string) error {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
if !w.cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromServerList()
|
||||
message := template.Render(cfg.ControllerMessage.ServerList, params, s.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerList, params, w.cfg.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"type": "serverList",
|
||||
@@ -148,14 +109,13 @@ func (w *WebhookController) SendServerList(onlineServers, offlineServers string)
|
||||
|
||||
// SendExecuteResult sends a command execution result via Webhook.
|
||||
func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, result string) error {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
if !w.cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
|
||||
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, s.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, w.cfg.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"type": "executeResult",
|
||||
@@ -173,8 +133,7 @@ func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, r
|
||||
// SendAlert sends an alert submitted through the incoming webhook API to the
|
||||
// configured URL.
|
||||
func (w *WebhookController) SendAlert(alert controller.Alert) error {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
if !w.cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -183,20 +142,15 @@ func (w *WebhookController) SendAlert(alert controller.Alert) error {
|
||||
"subject": alert.Subject,
|
||||
"source": alert.Source,
|
||||
"content": alert.Content,
|
||||
"message": alert.Render(s.Markdown),
|
||||
"message": alert.Render(w.cfg.Markdown),
|
||||
"time": alert.Time,
|
||||
}
|
||||
|
||||
return w.send(payload)
|
||||
}
|
||||
|
||||
// send posts one payload using the settings in effect at the moment it is
|
||||
// called, so the URL, method and headers all come from the same configuration
|
||||
// even if a reload lands mid-send.
|
||||
func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
s := w.settings()
|
||||
|
||||
method := s.Method
|
||||
method := w.cfg.Method
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
@@ -206,17 +160,17 @@ func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
return fmt.Errorf("failed to marshal webhook payload: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, s.URL, bytes.NewReader(bodyJSON))
|
||||
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 s.Headers {
|
||||
for key, value := range w.cfg.Headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := w.client().Do(req)
|
||||
resp, err := w.httpClient.Do(req)
|
||||
if err != nil {
|
||||
postLog.Warning("Failed to send webhook: " + err.Error())
|
||||
return err
|
||||
@@ -227,6 +181,6 @@ func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
postLog.Warning(fmt.Sprintf("Webhook returned status %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
postLog.Debug("Webhook notification sent to " + s.URL)
|
||||
postLog.Debug("Webhook notification sent to " + w.cfg.URL)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user