refactor(controller): apply controller settings by rebuilding the channel set
Build / ubuntu-latest (push) Canceled after 20s
Build / windows-latest (push) Canceled after 24s

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:
2026-09-28 23:21:35 +08:00
parent 0691e85ccf
commit 2a5a46a984
13 changed files with 508 additions and 604 deletions
+29 -70
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"net/http"
"strings"
"sync/atomic"
"time"
"nukumizu-backend/config"
@@ -17,32 +16,21 @@ import (
// NtfyController handles notifications via ntfy.sh or a self-hosted ntfy server.
//
// 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 NtfyController struct {
cfg atomic.Pointer[config.NtfyConfig]
httpClient atomic.Pointer[http.Client]
cfg config.NtfyConfig
httpClient *http.Client
}
// NewNtfyController creates a new Ntfy controller.
func NewNtfyController(cfg config.NtfyConfig) *NtfyController {
n := &NtfyController{}
n.cfg.Store(&cfg)
n.httpClient.Store(netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second))
return n
}
// 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 (n *NtfyController) settings() *config.NtfyConfig {
return n.cfg.Load()
}
// client returns the HTTP client built for the current proxy setting.
func (n *NtfyController) client() *http.Client {
return n.httpClient.Load()
return &NtfyController{
cfg: cfg,
httpClient: netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second),
}
}
// Name returns the controller name.
@@ -52,7 +40,7 @@ func (n *NtfyController) Name() string {
// Start initializes the Ntfy controller.
func (n *NtfyController) Start() error {
if !n.settings().Enabled {
if !n.cfg.Enabled {
postLog.Info("Ntfy controller is disabled")
return nil
}
@@ -65,50 +53,26 @@ func (n *NtfyController) Stop() {
postLog.Info("Ntfy controller stopped")
}
// Reload applies the current configuration. Everything the publisher 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 (n *NtfyController) Reload() {
global := config.Current()
if global == nil {
return
}
current := n.settings()
updated := global.ControllerMethod.Ntfy
if *current == updated {
return
}
if current.NetworkUseProxy != updated.NetworkUseProxy {
n.httpClient.Store(netproxy.HTTPClient(updated.NetworkUseProxy, 10*time.Second))
}
n.cfg.Store(&updated)
postLog.Debug("Ntfy controller reloaded")
}
// IsEnabled returns whether the controller is enabled.
func (n *NtfyController) IsEnabled() bool {
return n.settings().Enabled
return n.cfg.Enabled
}
// IsMarkdown returns whether the channel renders Markdown, per its markdown
// setting in config.json.
func (n *NtfyController) IsMarkdown() bool {
return n.settings().Markdown
return n.cfg.Markdown
}
// SendStatusChange sends a status change notification via Ntfy.
func (n *NtfyController) SendStatusChange(change node.StatusChange) error {
s := n.settings()
if !s.Enabled {
if !n.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, n.cfg.Markdown)
title := fmt.Sprintf("Server %s: %s", change.Name, change.Event)
return n.publish(title, message)
@@ -116,28 +80,26 @@ func (n *NtfyController) SendStatusChange(change node.StatusChange) error {
// SendServerList sends the server list via Ntfy.
func (n *NtfyController) SendServerList(onlineServers, offlineServers string) error {
s := n.settings()
if !s.Enabled {
if !n.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, n.cfg.Markdown)
return n.publish("Server List", message)
}
// SendExecuteResult sends a command execution result via Ntfy.
func (n *NtfyController) SendExecuteResult(serverName, serverUUID, command, result string) error {
s := n.settings()
if !s.Enabled {
if !n.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, n.cfg.Markdown)
title := fmt.Sprintf("Command Result: %s on %s", command, serverName)
return n.publish(title, message)
@@ -146,24 +108,21 @@ func (n *NtfyController) SendExecuteResult(serverName, serverUUID, command, resu
// SendAlert sends an alert submitted through the incoming webhook API to the
// configured topic.
func (n *NtfyController) SendAlert(alert controller.Alert) error {
s := n.settings()
if !s.Enabled {
if !n.cfg.Enabled {
return nil
}
return n.publish(alert.Subject, alert.Render(s.Markdown))
return n.publish(alert.Subject, alert.Render(n.cfg.Markdown))
}
func (n *NtfyController) publish(title, message string) error {
s := n.settings()
serverURL := s.Server
serverURL := n.cfg.Server
if serverURL == "" {
serverURL = "https://ntfy.sh"
}
serverURL = strings.TrimRight(serverURL, "/")
publishURL := fmt.Sprintf("%s/%s", serverURL, s.Topic)
publishURL := fmt.Sprintf("%s/%s", serverURL, n.cfg.Topic)
req, err := http.NewRequest("POST", publishURL, strings.NewReader(message))
if err != nil {
@@ -171,14 +130,14 @@ func (n *NtfyController) publish(title, message string) error {
}
req.Header.Set("Title", title)
if s.Priority != "" && s.Priority != "default" {
req.Header.Set("Priority", s.Priority)
if n.cfg.Priority != "" && n.cfg.Priority != "default" {
req.Header.Set("Priority", n.cfg.Priority)
}
if s.Token != "" {
req.Header.Set("Authorization", "Bearer "+s.Token)
if n.cfg.Token != "" {
req.Header.Set("Authorization", "Bearer "+n.cfg.Token)
}
resp, err := n.client().Do(req)
resp, err := n.httpClient.Do(req)
if err != nil {
postLog.Warning("Failed to publish to ntfy: " + err.Error())
return err
@@ -189,6 +148,6 @@ func (n *NtfyController) publish(title, message string) error {
postLog.Warning(fmt.Sprintf("Ntfy publish returned status %d", resp.StatusCode))
}
postLog.Debug("Ntfy notification sent to topic: " + s.Topic)
postLog.Debug("Ntfy notification sent to topic: " + n.cfg.Topic)
return nil
}