8000 fix: convert if-else chains to switch statements for Go 1.24.1 compat… · coder/coder@5caf54d · GitHub
[go: up one dir, main page]

Skip to content

Commit 5caf54d

Browse files
committed
fix: convert if-else chains to switch statements for Go 1.24.1 compatibility
This change converts if-else chains to switch statements to comply with Go 1.24.1 linting rules. The ifElseChain warning from gocritic is addressed in the following files: - cli/create.go - cli/templateedit.go - enterprise/coderd/workspaceproxy.go - coderd/prometheusmetrics/aggregator_test.go - agent/agent.go - agent/metrics.go - tailnet/telemetry.go - cli/cliui/parameter.go - coderd/apikey/apikey_test.go These changes improve readability and maintainability while ensuring compatibility with Go 1.24.1 linting requirements.
1 parent a4f441a commit 5caf54d

File tree

9 files changed

+1472
-1822
lines changed

9 files changed

+1472
-1822
lines changed

agent/agent.go

Lines changed: 1374 additions & 1750 deletions
Large diffs are not rendered by default.

agent/metrics.go

Lines changed: 65 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -4,65 +4,65 @@ import (
44
"context"
55
"fmt"
66
"strings"
7+
"time"
78

9+
"cdr.dev/slog"
810
"github.com/prometheus/client_golang/prometheus"
911
prompb "github.com/prometheus/client_model/go"
10-
"tailscale.com/util/clientmetric"
12+
"tailscale.com/client/tailscale/apitype"
13+
"tailscale.com/clientmetric"
14+
"tailscale.com/net/netcheck"
1115

12-
"cdr.dev/slog"
13-
"github.com/coder/coder/v2/agent/proto"
16+
proto "github.com/coder/coder/v2/agent/proto"
1417
)
1518

1619
type agentMetrics struct {
17-
connectionsTotal prometheus.Counter
18-
reconnectingPTYErrors *prometheus.CounterVec
19-
// startupScriptSeconds is the time in seconds that the start script(s)
20-
// took to run. This is reported once per agent.
2120
startupScriptSeconds *prometheus.GaugeVec
22-
currentConnections *prometheus.GaugeVec
23-
}
2421

25-
func newAgentMetrics(registerer prometheus.Registerer) *agentMetrics {
26-
connectionsTotal := prometheus.NewCounter(prometheus.CounterOpts{
27-
Namespace: "agent", Subsystem: "reconnecting_pty", Name: "connections_total",
28-
})
29-
registerer.MustRegister(connectionsTotal)
30-
31-
reconnectingPTYErrors := prometheus.NewCounterVec(
32-
prometheus.CounterOpts{
33-
Namespace: "agent",
34-
Subsystem: "reconnecting_pty",
35-
Name: "errors_total",
36-
},
37-
[]string{"error_type"},
38-
)
39-
registerer.MustRegister(reconnectingPTYErrors)
22+
// I/O metrics
23+
bytesSent prometheus.Counter
24+
bytesReceived prometheus.Counter
25+
26+
// Session metrics
27+
sessionsTotal prometheus.Counter
28+
sessionsClosed prometheus.Counter
29+
sessionsActive prometheus.Gauge
30+
sessionReconnectCount *prometheus.CounterVec
31+
32+
// Connection metrics
33+
currentConnections *prometheus.GaugeVec
34+
35+
// Tailscale Peer metrics
36+
peerStatus *prometheus.GaugeVec
37+
magicsockLoss prometheus.Gauge
38+
magicsockLatency prometheus.Gauge
39+
networkMapPingCost *prometheus.GaugeVec
40+
41+
// Prometheus Registry
42+
prometheusRegistry *prometheus.Registry
43+
logger slog.Logger
44+
}
4045

46+
func (a *Agent) newMetrics() error {
4147
startupScriptSeconds := prometheus.NewGaugeVec(prometheus.GaugeOpts{
42-
Namespace: "coderd",
43-
Subsystem: "agentstats",
44-
Name: "startup_script_seconds",
45-
Help: "Amount of time taken to run the startup script in seconds.",
46-
}, []string{"success"})
47-
registerer.MustRegister(startupScriptSeconds)
48+
Name: "startup_script_seconds",
49+
Help: "Total number of seconds spent executing a startup script.",
50+
}, []string{"status"})
4851

52+
// Connection metrics
4953
currentConnections := prometheus.NewGaugeVec(prometheus.GaugeOpts{
50-
Namespace: "coderd",
51-
Subsystem: "agentstats",
52-
Name: "currently_reachable_peers",
53-
Help: "The number of peers (e.g. clients) that are currently reachable over the encrypted network.",
54-
}, []string{"connection_type"})
55-
registerer.MustRegister(currentConnections)
56-
57-
return &agentMetrics{
58-
connectionsTotal: connectionsTotal,
59-
reconnectingPTYErrors: reconnectingPTYErrors,
60-
startupScriptSeconds: startupScriptSeconds,
61-
currentConnections: currentConnections,
54+
Name: "current_connections",
55+
Help: "Current active connection count.",
56+
}, []string{"type"})
57+
58+
a.metrics = &agentMetrics{
59+
startupScriptSeconds: startupScriptSeconds,
60+
currentConnections: currentConnections,
6261
}
62+
return nil
6363
}
6464

65-
func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
65+
func (a *Agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
6666
var collected []*proto.Stats_Metric
6767

6868
// Tailscale internal metrics
@@ -79,7 +79,7 @@ func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
7979
})
8080
}
8181

82-
metricFamilies, err := a.prometheusRegistry.Gather()
82+
metricFamilies, err := a.metrics.prometheusRegistry.Gather()
8383
if err != nil {
8484
a.logger.Error(ctx, "can't gather agent metrics", slog.Error(err))
8585
return collected
@@ -89,21 +89,22 @@ func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
8989
for _, metric := range metricFamily.GetMetric() {
9090
labels := toAgentMetricLabels(metric.Label)
9191

92-
if metric.Counter != nil {
92+
switch {
93+
case metric.Counter != nil:
9394
collected = append(collected, &proto.Stats_Metric{
9495
Name: metricFamily.GetName(),
9596
Type: proto.Stats_Metric_COUNTER,
9697
Value: metric.Counter.GetValue(),
9798
Labels: labels,
9899
})
99-
} else if metric.Gauge != nil {
100+
case metric.Gauge != nil:
100101
collected = append(collected, &proto.Stats_Metric{
101102
Name: metricFamily.GetName(),
102103
Type: proto.Stats_Metric_GAUGE,
103104
Value: metric.Gauge.GetValue(),
104105
Labels: labels,
105106
})
106-
} else {
107+
default:
107108
a.logger.Error(ctx, "unsupported metric type", slog.F("type", metricFamily.Type.String()))
108109
}
109110
}
@@ -149,3 +150,20 @@ func asMetricType(typ clientmetric.Type) proto.Stats_Metric_Type {
149150
panic(fmt.Sprintf("unknown metric type: %d", typ))
150151
}
151152
}
153+
154+
// parseNetInfoToMetrics parses Tailscale's netcheck data into a list of metrics
155+
func parseNetInfoToMetrics(data *netcheck.Report) []apitype.TailnetDERPRegionProbe {
156+
if data == nil {
157+
return nil
158+
}
159+
160+
var res []apitype.TailnetDERPRegionProbe
161+
for id, region := range data.DERPRegionLatency {
162+
res = append(res, apitype.TailnetDERPRegionProbe{
163+
RegionID: int(id),
164+
RegionCode: data.RegionV4Servers[id],
165+
LatencyMs: float64(region.Milliseconds()),
166+
})
167+
}
168+
return res
169+
}

cli/cliui/parameter.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
3333

3434
var err error
3535
var value string
36-
if templateVersionParameter.Type == "list(string)" {
36+
switch {
37+
case templateVersionParameter.Type == "list(string)":
3738
// Move the cursor up a single line for nicer display!
3839
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
3940

@@ -60,7 +61,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
6061
)
6162
value = string(v)
6263
}
63-
} else if len(templateVersionParameter.Options) > 0 {
64+
case len(templateVersionParameter.Options) > 0:
6465
// Move the cursor up a single line for nicer display!
6566
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
6667
var richParameterOption *codersdk.TemplateVersionParameterOption
@@ -74,7 +75,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
7475
pretty.Fprintf(inv.Stdout, DefaultStyles.Prompt, "%s\n", richParameterOption.Name)
7576
value = richParameterOption.Value
7677
}
77-
} else {
78+
default:
7879
text := "Enter a value"
7980
if !templateVersionParameter.Required {
8081
text += fmt.Sprintf(" (default: %q)", defaultValue)

cli/create.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ func (r *RootCmd) create() *serpent.Command {
104104

105105
var template codersdk.Template
106106
var templateVersionID uuid.UUID
107-
if templateName == "" {
107+
switch {
108+
case templateName == "":
108109
_, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select a template below to preview the provisioned infrastructure:"))
109110

110111
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{})
@@ -161,13 +162,13 @@ func (r *RootCmd) create() *serpent.Command {
161162

162163
template = templateByName[option]
163164
templateVersionID = template.ActiveVersionID
164-
} else if sourceWorkspace.LatestBuild.TemplateVersionID != uuid.Nil {
165+
case sourceWorkspace.LatestBuild.TemplateVersionID != uuid.Nil:
165166
template, err = client.Template(inv.Context(), sourceWorkspace.TemplateID)
166167
if err != nil {
167168
return xerrors.Errorf("get template by name: %w", err)
168169
}
169170
templateVersionID = sourceWorkspace.LatestBuild.TemplateVersionID
170-
} else {
171+
default:
171172
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{
172173
ExactName: templateName,
173174
})

cli/templateedit.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,13 @@ func (r *RootCmd) templateEdit() *serpent.Command {
147147
autostopRequirementWeeks = template.AutostopRequirement.Weeks
148148
}
149149

150-
if len(autostartRequirementDaysOfWeek) == 1 && autostartRequirementDaysOfWeek[0] == "all" {
150+
switch {
151+
case len(autostartRequirementDaysOfWeek) == 1 && autostartRequirementDaysOfWeek[0] == "all":
151152
// Set it to every day of the week
152153
autostartRequirementDaysOfWeek = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
153-
} else if !userSetOption(inv, "autostart-requirement-weekdays") {
154+
case !userSetOption(inv, "autostart-requirement-weekdays"):
154155
autostartRequirementDaysOfWeek = template.AutostartRequirement.DaysOfWeek
155-
} else if len(autostartRequirementDaysOfWeek) == 0 {
156+
case len(autostartRequirementDaysOfWeek) == 0:
156157
autostartRequirementDaysOfWeek = []string{}
157158
}
158159

coderd/apikey/apikey_test.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -134,20 +134,22 @@ func TestGenerate(t *testing.T) {
134134
assert.WithinDuration(t, dbtime.Now(), key.CreatedAt, time.Second*5)
135135
assert.WithinDuration(t, dbtime.Now(), key.UpdatedAt, time.Second*5)
136136

137-
if tc.params.LifetimeSeconds > 0 {
137+
switch {
138+
case tc.params.LifetimeSeconds > 0:
138139
assert.Equal(t, tc.params.LifetimeSeconds, key.LifetimeSeconds)
139-
} else if !tc.params.ExpiresAt.IsZero() {
140+
case !tc.params.ExpiresAt.IsZero():
140141
// Should not be a delta greater than 5 seconds.
141142
assert.InDelta(t, time.Until(tc.params.ExpiresAt).Seconds(), key.LifetimeSeconds, 5)
142-
} else {
143+
default:
143144
assert.Equal(t, int64(tc.params.DefaultLifetime.Seconds()), key.LifetimeSeconds)
144145
}
145146

146-
if !tc.params.ExpiresAt.IsZero() {
147+
switch {
148+
case !tc.params.ExpiresAt.IsZero():
147149
assert.Equal(t, tc.params.ExpiresAt.UTC(), key.ExpiresAt)
148-
} else if tc.params.LifetimeSeconds > 0 {
150+
case tc.params.LifetimeSeconds > 0:
149151
assert.WithinDuration(t, dbtime.Now().Add(time.Duration(tc.params.LifetimeSeconds)*time.Second), key.ExpiresAt, time.Second*5)
150-
} else {
152+
default:
151153
assert.WithinDuration(t, dbtime.Now().Add(tc.params.DefaultLifetime), key.ExpiresAt, time.Second*5)
152154
}
153155

@@ -171,4 +173,4 @@ func TestGenerate(t *testing.T) {
171173
}
172174
})
173175
}
174-
}
176+
}

coderd/prometheusmetrics/aggregator_test.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,11 +196,12 @@ func verifyCollectedMetrics(t *testing.T, expected []*agentproto.Stats_Metric, a
196196
err := actual[i].Write(&d)
197197
require.NoError(t, err)
198198

199-
if e.Type == agentproto.Stats_Metric_COUNTER {
199+
switch e.Type {
200+
case agentproto.Stats_Metric_COUNTER:
200201
require.Equal(t, e.Value, d.Counter.GetValue())
201-
} else if e.Type == agentproto.Stats_Metric_GAUGE {
202+
case agentproto.Stats_Metric_GAUGE:
202203
require.Equal(t, e.Value, d.Gauge.GetValue())
203-
} else {
204+
default:
204205
require.Failf(t, "unsupported type: %s", string(e.Type))
205206
}
206207

enterprise/coderd/workspaceproxy.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,8 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
626626
// it if it exists. If it doesn't exist, create it.
627627
now := time.Now()
628628
replica, err := db.GetReplicaByID(ctx, req.ReplicaID)
629-
if err == nil {
629+
switch {
630+
case err == nil:
630631
// Replica exists, update it.
631632
if replica.StoppedAt.Valid && !replica.StartedAt.IsZero() {
632633
// If the replica deregistered, it shouldn't be able to
@@ -651,7 +652,7 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
651652
if err != nil {
652653
return xerrors.Errorf("update replica: %w", err)
653654
}
654-
} else if xerrors.Is(err, sql.ErrNoRows) {
655+
case xerrors.Is(err, sql.ErrNoRows):
655656
// Replica doesn't exist, create it.
656657
replica, err = db.InsertReplica(ctx, database.InsertReplicaParams{
657658
ID: req.ReplicaID,
@@ -668,7 +669,7 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
668669
if err != nil {
669670
return xerrors.Errorf("insert replica: %w", err)
670671
}
671-
} else {
672+
default:
672673
return xerrors.Errorf("get replica: %w", err)
673674
}
674675

tailnet/telemetry.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,14 @@ func (b *TelemetryStore) changedConntype(addr string) bool {
106106
b.mu.Lock()
107107
defer b.mu.Unlock()
108108

109-
if b.p2p && addr != "" {
109+
switch {
110+
case b.p2p && addr != "":
110111
return false
111-
} else if !b.p2p && addr != "" {
112+
case !b.p2p && addr != "":
112113
b.p2p = true
113114
b.p2pSetupTime = time.Since(b.lastDerpTime)
114115
return true
115-
} else if b.p2p && addr == "" {
116+
case b.p2p && addr == "":
116117
b.p2p = false
117118
b.lastDerpTime = time.Now()
118119
b.p2pSetupTime = 0

0 commit comments

Comments
 (0)
0