Files
NanamiAdmin 2a5a46a984
Build / ubuntu-latest (push) Canceled after 20s
Build / windows-latest (push) Canceled after 24s
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".
2026-09-28 23:21:35 +08:00

187 lines
4.8 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.
//
// 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 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
}