Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions core/cmd/mistgate-clientd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,9 @@ func keepLastUp(statuses <-chan session.Event, store *settings.Store) {
}

// A panel that issued a new key leaves a connected client with auth_rejected until its next scheduled sync, and the
// session would give up first. One sync of that subscription fetches the new profiles for the next attempt. The panel
// allows 30 requests an hour per device: one in this window is at most 6.
// session would give up first. One sync of that subscription fetches the new profiles for the next attempt. The same
// goes for a session that no server answers: the paths may have changed. The panel allows 30 requests an hour per
// device: one in this window is at most 6, and both causes share it.
const refreshAfterRejection = 10 * time.Minute

// subscriptionOf is the subscription of the server a status names; the one the person connected through when the status
Expand All @@ -149,21 +150,22 @@ func subscriptionOf(list []subs.Subscription, serverID, lastSub string) string {
return lastSub
}

// refreshOnRejection asks for a refresh of the subscription when a connect or reconnect is refused for its key, at most
// once per window for each subscription. refresh must not wait for the network: this loop drains the session's events.
func refreshOnRejection(statuses <-chan session.Event, subOf func(serverID string) string, refresh func(sub string), now func() time.Time) {
// refreshOnRejection asks for a refresh of the subscription when a connect or reconnect is refused for its key, or when
// no server answered (noAnswer), at most once per window for each subscription. refresh must not wait for the network:
// this loop drains the session's events.
func refreshOnRejection(statuses <-chan session.Event, subOf func(serverID string) string, refresh func(sub string, noAnswer bool), now func() time.Time) {
last := make(map[string]time.Time)
for event := range statuses {
status, ok := event.Data.(session.Status)
if !ok || status.Error != "auth_rejected" || status.State != "reconnecting" && status.State != "error" {
if !ok || status.Error != "auth_rejected" && status.Error != "no_server_answers" || status.State != "reconnecting" && status.State != "error" {
continue
}
sub := subOf(status.ServerID)
if at, asked := last[sub]; sub == "" || asked && now().Sub(at) < refreshAfterRejection {
continue
}
last[sub] = now()
refresh(sub)
refresh(sub, status.Error == "no_server_answers")
}
}

Expand Down Expand Up @@ -374,8 +376,15 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents
if statuses, err := manager.Events().Subscribe([]string{"status"}); err == nil {
go refreshOnRejection(statuses.C, func(serverID string) string {
return subscriptionOf(store.List(), serverID, settingsStore.Get().LastSub)
}, func(sub string) {
go store.Refresh(ctx, sub) // the store tells the session when the profiles changed
}, func(sub string, noAnswer bool) {
go func() {
if !noAnswer {
store.Refresh(ctx, sub) // the store tells the session when the profiles changed
return
}
manager.Resync("running")
manager.Resync(store.Resync(ctx, sub))
}()
}, time.Now)
}
if configured := settingsStore.Get(); shouldResumeAtStart(configured) || shouldConnectAtStart(configured) {
Expand Down
29 changes: 26 additions & 3 deletions core/cmd/mistgate-clientd/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func TestRefreshOnRejectionAsksOncePerWindow(t *testing.T) {
go func() {
defer close(done)
refreshOnRejection(statuses, func(serverID string) string { return subscriptionOf(list, serverID, "") },
func(sub string) { asked = append(asked, sub) }, func() time.Time { return at })
func(sub string, _ bool) { asked = append(asked, sub) }, func() time.Time { return at })
}()
// an event that is no status: once the loop has taken it, it is done with the one before
send := func(event session.Event) {
Expand Down Expand Up @@ -139,7 +139,9 @@ func TestRefreshOnRejectionAsksOncePerWindow(t *testing.T) {

func TestRefreshOnRejectionIgnoresOtherStatuses(t *testing.T) {
events := []session.Event{
{Name: "status", Data: session.Status{State: "reconnecting", Error: "no_server_answers", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "reconnecting", Error: "offline", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "error", Error: "server_not_found", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "connected", Error: "no_server_answers", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "connected", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "blocked", Error: "auth_rejected", ServerID: "path-a"}},
{Name: "status", Data: session.Status{State: "reconnecting", Error: "auth_rejected"}}, // no server, no last subscription
Expand All @@ -149,7 +151,28 @@ func TestRefreshOnRejectionIgnoresOtherStatuses(t *testing.T) {
statuses <- event
}
close(statuses)
refreshOnRejection(statuses, func(string) string { return "" }, func(sub string) { t.Errorf("refreshed %q", sub) }, time.Now)
refreshOnRejection(statuses, func(string) string { return "" }, func(sub string, _ bool) { t.Errorf("refreshed %q", sub) }, time.Now)
}

// No server answered is a cause of its own, with the same window per subscription as a refused key: whichever came
// first used the request, and the one that came inside the window did not.
func TestRefreshOnNoAnswerSharesTheWindowWithRejection(t *testing.T) {
status := func(state, code string) session.Event {
return session.Event{Name: "status", Data: session.Status{State: state, Error: code, ServerID: "path-a"}}
}
list := []subs.Subscription{{ID: "s1", Servers: []subs.Server{{ID: "path-a"}}}}
at := time.Unix(1_700_000_000, 0)
var asked []bool
statuses := make(chan session.Event, 8)
for _, event := range []session.Event{status("reconnecting", "no_server_answers"), status("error", "auth_rejected")} {
statuses <- event
}
close(statuses)
refreshOnRejection(statuses, func(serverID string) string { return subscriptionOf(list, serverID, "") },
func(sub string, noAnswer bool) { asked = append(asked, noAnswer) }, func() time.Time { return at })
if !slices.Equal(asked, []bool{true}) {
t.Fatalf("asked %v, want one request, for no answer, and none for the refusal inside its window", asked)
}
}

func TestSubscriptionOf(t *testing.T) {
Expand Down
25 changes: 25 additions & 0 deletions core/internal/session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ type Status struct {
// Auto: the path in use was picked by Auto (not named by the person). Reason is why: known, only, failover or fastest.
Auto bool `json:"auto,omitempty"`
Reason string `json:"reason,omitempty"`
// Resync: the service asked the panel for the subscription again because no server answered: "running", then how it
// ended: "changed" (other settings, a new attempt is made at once), "same" or "failed". ResyncUnix is when it was set.
Resync string `json:"resync,omitempty"`
ResyncUnix int64 `json:"resync_unix,omitempty"`
}

type RouteState struct {
Expand Down Expand Up @@ -86,6 +90,7 @@ type resumeRequest struct {
}
type settingsChangedRequest struct{}
type subscriptionsChangedRequest struct{}
type resyncRequest struct{ result string }
type networkChangedRequest struct {
reason string
asleep time.Duration
Expand Down Expand Up @@ -342,6 +347,16 @@ func (m *Manager) SubscriptionsChanged() {
}
}

// Resync tells the session that the subscription was asked for again after no server answered ("running"), and what
// came of it ("changed", "same", "failed"). Only a session that is trying to connect keeps it; "changed" starts the next
// attempt at once, as a change of network does.
func (m *Manager) Resync(result string) {
select {
case m.commands <- resyncRequest{result}:
case <-m.done:
}
}

func (m *Manager) NetworkChanged(reason string, asleep time.Duration) {
select {
case m.commands <- networkChangedRequest{reason: reason, asleep: asleep}:
Expand Down Expand Up @@ -531,6 +546,15 @@ func (m *Manager) run() {
m.settingsChanged(&state)
case subscriptionsChangedRequest:
m.subscriptionsChanged(&state)
case resyncRequest:
if state.status.State == "connecting" || state.status.State == "reconnecting" || state.status.State == "error" {
state.status.Resync, state.status.ResyncUnix = request.result, time.Now().Unix()
m.hub.Publish("status", state.status)
if request.result == "changed" && state.status.State == "reconnecting" {
clearTimer(&retryTimer, &retryC)
m.networkChanged(&state, "resync", 0, time.Now())
}
}
case networkChangedRequest:
clearTimer(&healthTimer, &healthC)
clearTimer(&retryTimer, &retryC)
Expand Down Expand Up @@ -670,6 +694,7 @@ func (m *Manager) run() {
} else {
state.status.State = "connected"
state.status.Error = ""
state.status.Resync, state.status.ResyncUnix = "", 0
state.status.Server = request.info.Server
state.status.ServerID = request.info.ServerID
state.status.Protocol = request.info.Protocol
Expand Down
26 changes: 26 additions & 0 deletions core/internal/session/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func TestSessionScenarios(t *testing.T) {
{name: "boot connect retries, a human connect does not", run: testBootConnectRetries},
{name: "a human connect over a waiting boot connect", run: testBootConnectGivesWayToAHuman},
{name: "no_subscription stops the engine and ends in error", run: testNoSubscriptionStopsTheEngine},
{name: "a resync reports its result and a changed one retries at once", run: testResyncRetriesWhenChanged},
{name: "always unavailable hold is not reported as blocked", run: testAlwaysUnavailableHoldIsNotBlocked},
{name: "settings changes apply hold transitions", run: testSettingsChangesApplyHoldTransitions},
{name: "off reconnect does not hold", run: testOffReconnectDoesNotHold},
Expand Down Expand Up @@ -1360,3 +1361,28 @@ func receiveStatus(t *testing.T, events <-chan Event) Status {
return Status{}
}
}

// After no server answered, the service asks the panel again and tells the session how it ended: the status carries it,
// and only other settings ("changed") start the next attempt before the backoff is over.
func testResyncRetriesWhenChanged(t *testing.T) {
fake := engine.NewFake(engine.FakeConfig{StepDelay: time.Millisecond, FailStartCode: "no_server_answers"})
manager, subscription := retryManager(t, fake, "always", time.Hour)
if _, err := manager.Connect(context.Background(), engine.Target{}); err != nil {
t.Fatal(err)
}
waitForStatus(t, subscription.C, func(status Status) bool { return status.State == "reconnecting" && status.Error == "no_server_answers" })
manager.Resync("running")
waitForStatus(t, subscription.C, func(status Status) bool { return status.Resync == "running" && status.ResyncUnix != 0 })
manager.Resync("same")
waitForStatus(t, subscription.C, func(status Status) bool { return status.Resync == "same" })
time.Sleep(50 * time.Millisecond)
if got := fake.StartCount(); got != 1 {
t.Fatalf("Start() calls = %d, want no attempt before the backoff is over", got)
}
fake.SetFailStartCode("")
manager.Resync("changed")
status := waitForStatus(t, subscription.C, func(status Status) bool { return status.State == "connected" })
if got := fake.StartCount(); got != 2 || status.Resync != "" {
t.Fatalf("Start() calls = %d, resync = %q; want a new attempt at once and no resync once connected", got, status.Resync)
}
}
32 changes: 32 additions & 0 deletions core/internal/subs/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -882,3 +882,35 @@ func TestClientAPITrustTunnelPaths(t *testing.T) {
}
t.Fatal("stored TrustTunnel path not found")
}

func TestResyncSaysHowItEnded(t *testing.T) {
ctx := context.Background()
panel, store, sub := managedStore(t)
other := syncDoc("active", apiServer("Rome", "IT", apiPath("pth_2", "hysteria2", "direct", false, map[string]any{
"server": "rome.example", "port": 443, "auth": "api-auth-rome", "tls": "ca",
})))
panel.set(func() { panel.etag = `"v1"` })
if got := store.Resync(ctx, sub.ID); got != "same" { // a new tag over the same paths is not a change
t.Fatalf("new etag, same paths = %q, want same", got)
}
if got := store.Resync(ctx, sub.ID); got != "same" { // 304
t.Fatalf("304 = %q, want same", got)
}
panel.set(func() { panel.etag, panel.syncBody = `"v2"`, other })
if got := store.Resync(ctx, sub.ID); got != "changed" {
t.Fatalf("other etag = %q, want changed", got)
}
panel.set(func() { panel.etag, panel.syncBody = "", syncDoc("active") })
store.Resync(ctx, sub.ID) // the tag is gone: from here on the paths tell
if got := store.Resync(ctx, sub.ID); got != "same" {
t.Fatalf("same paths without a tag = %q, want same", got)
}
panel.set(func() { panel.syncBody = other })
if got := store.Resync(ctx, sub.ID); got != "changed" {
t.Fatalf("other paths without a tag = %q, want changed", got)
}
panel.set(func() { panel.syncStatus, panel.errBody = 503, "<html>down</html>" })
if got := store.Resync(ctx, sub.ID); got != "failed" {
t.Fatalf("panel down = %q, want failed", got)
}
}
30 changes: 30 additions & 0 deletions core/internal/subs/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,36 @@ func (s *Store) Refresh(ctx context.Context, id string) (Subscription, error) {
return s.refresh(ctx, id)
}

// Resync is Refresh for a session that could reach no server, and says how it ended: "changed" when the panel gave other
// paths (the ETag is not asked: it covers more of the answer than the paths), "same" for a 304 or the same paths, "failed"
// when it gave nothing.
func (s *Store) Resync(ctx context.Context, id string) string {
s.opMu.Lock()
defer s.opMu.Unlock()
raws := s.pathRaws(id)
if _, err := s.refresh(ctx, id); err != nil {
return "failed"
}
if !slices.Equal(s.pathRaws(id), raws) {
return "changed"
}
return "same"
}

func (s *Store) pathRaws(id string) (raws []string) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, sub := range s.state.Subscriptions {
if sub.ID == id {
for _, entry := range sub.Entries {
raws = append(raws, entry.Raw)
}
return raws
}
}
return nil
}

func (s *Store) refresh(ctx context.Context, id string) (Subscription, error) {
s.mu.RLock()
var current storedSubscription
Expand Down
Loading
Loading