mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-09 21:00:58 +00:00
5bc81dfd1d
A client that hit its quota or expiry was disabled, then destroyed on both panels a few seconds later. Five defects fed the same hard delete. ReconcileNode pushed buildRuntimeInboundForAPI, which strips disabled clients. Every other call site targets an in-memory Xray config, where dropping a user is harmless; a node target is a peer panel's DATABASE, so the node deleted the row, stopped reporting it, and the master mirrored that deletion back. Split the builder in two: buildInboundForNodePush injects fallbacks only, buildInboundForLocalRuntime adds the strip on top. The names now say which targets they are safe for. setRemoteTrafficLocked trusted a config_dirty the caller sampled before the snapshot round-trip. A client added inside that window commits on the same serialized writer and marks the node dirty, but the merge still treated the older snapshot as authoritative and deleted it. Re-read the flag inside the writer. In "selected" sync mode, FilterNodeSnapshot strips a deselected tag, but the sweep loaded every inbound with node_id set, so deselecting a tag read as "the node deleted it" and wiped an inbound the node still serves. Skip tags outside the node's managed set. A failed SyncInbound was logged and swallowed; on SQLite the transaction still commits, and the sweep then deleted the innocent clients whose links that failure had left unbuilt. Skip the sweep for such an inbound, and close the trigger: SyncInbound now stores the trimmed email it looks up by, and email validation rejects every unicode space rather than only U+0020. ClientService.Delete tombstones up front and deliberately keeps the record when an inbound fails, so the next attempt can retry the leftovers. The tombstone did not lift with it, so the next merge dropped the client from the synced settings and finished the deletion this path had refused. Add withdrawClientTombstones on every failure path, in BulkDelete too. Finally, make the sweep itself recoverable. "Ended the merge unattached" is true for a real remote deletion and equally true for a bad merge, so it now stamps sync_orphaned_at instead of deleting; any later merge that sees the client attached clears the mark, and a reaper removes only what stayed orphaned past the grace period. The traffic row survives that window too, or a reclaimed client would come back with its usage, quota and expiry reset. The mark is written by this sweep alone, so orphans from any other cause keep their existing manual-cleanup semantics.
158 lines
4.8 KiB
Go
158 lines
4.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/mtproto"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
)
|
|
|
|
// DesiredMtprotoInstances derives the mtg sidecar configs this panel should be
|
|
// running: one instance per enabled local mtproto inbound, serving only the
|
|
// secrets of clients that are both enabled in the inbound settings and not
|
|
// depletion-disabled in client_traffics. That is the same effective client set
|
|
// buildInboundForLocalRuntime pushes on interactive edits, so the reconcile job
|
|
// and the push paths agree on one fingerprint — a disagreement would surface
|
|
// as a needless mtg restart, and a job that read only the raw settings would
|
|
// keep serving depleted clients until an unrelated restart. Inbounds whose
|
|
// every secret is filtered away are omitted so Reconcile stops their sidecar.
|
|
func (s *InboundService) DesiredMtprotoInstances() ([]mtproto.Instance, error) {
|
|
db := database.GetDB()
|
|
var inbounds []*model.Inbound
|
|
err := db.Model(model.Inbound{}).
|
|
Where("protocol = ? AND enable = ? AND node_id IS NULL", model.MTProto, true).
|
|
Find(&inbounds).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(inbounds) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
ids := make([]int, 0, len(inbounds))
|
|
for _, ib := range inbounds {
|
|
ids = append(ids, ib.Id)
|
|
}
|
|
var disabledRows []xray.ClientTraffic
|
|
err = db.Model(xray.ClientTraffic{}).
|
|
Where("inbound_id IN ? AND enable = ?", ids, false).
|
|
Select("inbound_id", "email").
|
|
Find(&disabledRows).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
disabled := make(map[int]map[string]struct{}, len(disabledRows))
|
|
for _, row := range disabledRows {
|
|
if disabled[row.InboundId] == nil {
|
|
disabled[row.InboundId] = map[string]struct{}{}
|
|
}
|
|
disabled[row.InboundId][row.Email] = struct{}{}
|
|
}
|
|
|
|
instances := make([]mtproto.Instance, 0, len(inbounds))
|
|
for _, ib := range inbounds {
|
|
inst, ok := mtproto.InstanceFromInbound(ib)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if off := disabled[ib.Id]; len(off) > 0 {
|
|
kept := make([]mtproto.SecretEntry, 0, len(inst.Secrets))
|
|
for _, sec := range inst.Secrets {
|
|
if _, skip := off[sec.Name]; !skip {
|
|
kept = append(kept, sec)
|
|
}
|
|
}
|
|
inst.Secrets = kept
|
|
}
|
|
if len(inst.Secrets) == 0 {
|
|
continue
|
|
}
|
|
instances = append(instances, inst)
|
|
}
|
|
return instances, nil
|
|
}
|
|
|
|
// applyLocalMtproto pushes a single local mtproto inbound's current client set
|
|
// to its mtg sidecar right after a client edit commits, so an add, removal,
|
|
// re-key or enable-toggle takes effect immediately instead of waiting up to
|
|
// 10s for the reconcile job. With a reload-capable mtg the change is applied in
|
|
// place without dropping other clients; older binaries fall back to a restart
|
|
// inside the manager. It re-reads the inbound so it sees the committed settings,
|
|
// filters depleted clients exactly like the reconcile job, and is a no-op for
|
|
// node-owned or non-mtproto inbounds. Failures are logged and swallowed: the
|
|
// reconcile job is the backstop, and an xray restart cannot help the sidecar.
|
|
func (s *InboundService) applyLocalMtproto(inboundId int) {
|
|
inbound, err := s.GetInbound(inboundId)
|
|
if err != nil || inbound == nil || inbound.Protocol != model.MTProto || inbound.NodeID != nil {
|
|
return
|
|
}
|
|
rt, err := s.runtimeFor(inbound)
|
|
if err != nil {
|
|
return
|
|
}
|
|
payload := inbound
|
|
if inbound.Enable {
|
|
if built, bErr := s.buildInboundForLocalRuntime(database.GetDB(), inbound); bErr == nil {
|
|
payload = built
|
|
}
|
|
}
|
|
if err := rt.UpdateInbound(context.Background(), inbound, payload); err != nil {
|
|
logger.Debug("mtproto: immediate client apply failed for inbound", inboundId, ":", err)
|
|
}
|
|
}
|
|
|
|
func (s *InboundService) resetMtprotoClientQuota(email string) {
|
|
mgr := mtproto.GetManager()
|
|
if !mgr.HasRunning() {
|
|
return
|
|
}
|
|
id, ok := s.localMtprotoInboundIdForEmail(email)
|
|
if !ok {
|
|
return
|
|
}
|
|
s.applyLocalMtproto(id)
|
|
mgr.ResetQuota(email)
|
|
}
|
|
|
|
func (s *InboundService) resetAllMtprotoQuotas() {
|
|
mgr := mtproto.GetManager()
|
|
if !mgr.HasRunning() {
|
|
return
|
|
}
|
|
desired, err := s.DesiredMtprotoInstances()
|
|
if err != nil {
|
|
return
|
|
}
|
|
mgr.Reconcile(desired)
|
|
for _, inst := range desired {
|
|
for _, sec := range inst.Secrets {
|
|
mgr.ResetQuota(sec.Name)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *InboundService) localMtprotoInboundIdForEmail(email string) (int, bool) {
|
|
db := database.GetDB()
|
|
var inbounds []*model.Inbound
|
|
if err := db.Model(model.Inbound{}).
|
|
Where("protocol = ? AND node_id IS NULL", model.MTProto).
|
|
Find(&inbounds).Error; err != nil {
|
|
return 0, false
|
|
}
|
|
for _, ib := range inbounds {
|
|
inst, ok := mtproto.InstanceFromInbound(ib)
|
|
if !ok {
|
|
continue
|
|
}
|
|
for _, sec := range inst.Secrets {
|
|
if sec.Name == email {
|
|
return ib.Id, true
|
|
}
|
|
}
|
|
}
|
|
return 0, false
|
|
}
|