Files
webui4frpc/internal/httpapi/handlers_forwards.go
jianf eda9bb9597 feat: cluster reliability (leader failover, crash rejoin, key exchange) + auth/users + canvas/forwards enhancements + comprehensive README + API docs
- Cluster: forwardToNext offline detection (leader+non-leader), WatchLeader 1s heartbeat fallback, 409 for standalone nodes, Node.NodeKey key exchange via token ring, ClusterPeers persistence + auto-rejoin, Forward delegates to forwardToNext (bugfix)
- Auth: Basic Auth (flag-creds fast path) + bcrypt users (admin/viewer) + Bearer API keys (read/write/admin scope)
- Frontend: UsersView (accounts+API keys), ClusterView (ring/nodeKey/tasks/topology/log), StatusView (group management, per-proxy status), CanvasView (edge toggle/group), PortEdge (disabled/group labels)
- API: handlers split (canvas/forwards/users/logs), canvas export/import, forwards group start/stop/assign/delete, cluster endpoints
- Docs: comprehensive README rewrite (all flags/APIs/auth/cluster), docs/cluster-api.md (cluster management API reference)
- Deploy: run-cluster.sh now 4-node ring + 1 isolated standalone, test-forward.sh updated for 4 nodes
- Removed plan.md (design notes consolidated into README + API docs)
2026-08-19 21:09:24 +08:00

279 lines
8.7 KiB
Go

package httpapi
import (
"encoding/json"
"net/http"
"webui4frpc/internal/store"
)
// forwardsReq is the {local,remote,remotePort} natural key identifying a single
// forward. The triple is stable across canvas re-saves (unlike Link.ID, which
// ReplaceLinks wholesale-replaces) and matches HasTask's keying.
type forwardsReq struct {
Local string `json:"local"`
Remote string `json:"remote"`
RemotePort int `json:"remotePort"`
}
// groupReq selects a group for one-click start/stop on the forwards page.
type groupReq struct {
Group string `json:"group"`
}
// findLinkByTriple returns the link matching the (local,remote,remotePort)
// natural key, or ok=false.
func findLinkByTriple(s *store.Store, local, remote string, port int) (store.Link, bool) {
links, err := s.ListLinks()
if err != nil {
return store.Link{}, false
}
for _, l := range links {
if l.Local == local && l.Remote == remote && l.RemotePort == port {
return l, true
}
}
return store.Link{}, false
}
// startForward flips a forward to enabled and brings it up. A local-only
// forward restarts/starts its local frpc worker so the re-enabled proxy is
// rendered back in; a cluster (non-localOnly) forward is submitted to the ring
// so the lowest-load member claims and spawns it (plan §令牌环协议). SubmitTask
// is idempotent via HasTask. Returns store.ErrNotFound if the forward is gone.
func (h *Handler) startForward(local, remote string, port int) error {
ln, ok := findLinkByTriple(h.Store, local, remote, port)
if !ok {
return store.ErrNotFound
}
loc, ok := h.Store.GetLocal(local)
if !ok {
return store.ErrNotFound
}
rem, ok := h.Store.GetRemote(remote)
if !ok {
return store.ErrNotFound
}
_ = h.Store.SetLinkDisabled(local, remote, port, false)
// Reflect the post-start (enabled) state in the snapshot handed to the
// ring: ln was fetched before SetLinkDisabled, so for a re-start of a
// previously stopped forward it still carries disabled=true. Without this
// the topology entry would embed a stale disabled flag (cosmetically
// wrong, and confusing if anything reads topology's link snapshot).
ln.Disabled = false
if loc.LocalOnly {
if h.Process != nil {
// Re-render (proxy re-added) on a running worker, or start it.
if _, has := h.Process.Status(remote); has {
_ = h.Process.Restart(remote)
} else {
_ = h.Process.Start(remote)
}
}
return nil
}
if h.Ring != nil {
h.Ring.SubmitTask(loc, rem, ln)
}
return nil
}
// stopForward flips a forward to disabled and tears it down. A local-only
// forward restarts its worker so renderRemote omits the proxy (sibling forwards
// on the same remote keep running — true per-forward stop); a cluster forward
// is revoked so the owning node cancels its worker and drops it from the
// topology (plan §任务撤销). RevokeTask is idempotent.
func (h *Handler) stopForward(local, remote string, port int) error {
ln, ok := findLinkByTriple(h.Store, local, remote, port)
if !ok {
return store.ErrNotFound
}
loc, ok := h.Store.GetLocal(local)
if !ok {
return store.ErrNotFound
}
rem, ok := h.Store.GetRemote(remote)
if !ok {
return store.ErrNotFound
}
_ = h.Store.SetLinkDisabled(local, remote, port, true)
if loc.LocalOnly {
// Re-render without this proxy; only meaningful while a worker runs.
if h.Process != nil {
if _, has := h.Process.Status(remote); has {
_ = h.Process.Restart(remote)
}
}
return nil
}
if h.Ring != nil {
h.Ring.RevokeTask(loc, rem, ln)
}
return nil
}
// handleForwardsStart toggles one forward on.
func (h *Handler) handleForwardsStart(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req forwardsReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
if req.Local == "" || req.Remote == "" || req.RemotePort <= 0 {
http.Error(w, "local/remote/remotePort required", http.StatusBadRequest)
return
}
if err := h.startForward(req.Local, req.Remote, req.RemotePort); err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// handleForwardsStop toggles one forward off.
func (h *Handler) handleForwardsStop(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req forwardsReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
if req.Local == "" || req.Remote == "" || req.RemotePort <= 0 {
http.Error(w, "local/remote/remotePort required", http.StatusBadRequest)
return
}
if err := h.stopForward(req.Local, req.Remote, req.RemotePort); err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// handleForwardsGroupStart starts every forward in a group with one click.
func (h *Handler) handleForwardsGroupStart(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req groupReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
links, err := h.Store.ListLinks()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, ln := range links {
if ln.Group != req.Group {
continue
}
_ = h.startForward(ln.Local, ln.Remote, ln.RemotePort)
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// handleForwardsGroupStop stops every forward in a group with one click.
func (h *Handler) handleForwardsGroupStop(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req groupReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
links, err := h.Store.ListLinks()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, ln := range links {
if ln.Group != req.Group {
continue
}
_ = h.stopForward(ln.Local, ln.Remote, ln.RemotePort)
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// assignReq carries the group label to assign to a single forward (status
// page group chip edit). Empty Group clears the assignment (移出分组).
type assignReq struct {
Local string `json:"local"`
Remote string `json:"remote"`
RemotePort int `json:"remotePort"`
Group string `json:"group"`
}
// handleForwardsAssign changes the group label of a single forward. The
// status page group chip is the quick entry; the canvas port editor also
// carries a group field (both persist via the same store column). The
// change is purely a DB update — no worker/ring action is needed (group is
// a management label, not a runtime knob).
func (h *Handler) handleForwardsAssign(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req assignReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
if req.Local == "" || req.Remote == "" || req.RemotePort <= 0 {
http.Error(w, "local/remote/remotePort required", http.StatusBadRequest)
return
}
if _, ok := findLinkByTriple(h.Store, req.Local, req.Remote, req.RemotePort); !ok {
http.Error(w, store.ErrNotFound.Error(), http.StatusNotFound)
return
}
if err := h.Store.SetLinkGroup(req.Local, req.Remote, req.RemotePort, req.Group); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// handleForwardsGroupDelete dissolves a group: every forward in the named
// group is moved to 未分组 (grp=""). The group itself is not a stored entity
// — it exists only as a label on links — so clearing all members is the
// complete "delete". No worker/ring action (group is a management label).
func (h *Handler) handleForwardsGroupDelete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
var req groupReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "parse json: "+err.Error(), http.StatusBadRequest)
return
}
if req.Group == "" {
http.Error(w, "group required", http.StatusBadRequest)
return
}
links, err := h.Store.ListLinks()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, ln := range links {
if ln.Group != req.Group {
continue
}
_ = h.Store.SetLinkGroup(ln.Local, ln.Remote, ln.RemotePort, "")
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}