Files
coder/codersdk/appname.go
T
Nick Vigilante 1ad46e48ac feat: report port-forward sessions as app usage (#30156)
`coder port-forward` reported usage with the deprecated
`UpdateWorkspaceUsageContext`.
It now reports a `port_forwarding` session, like `coder ssh` and the VS
Code SSH path, but only while a forwarded TCP connection is open.

**Behavior change:** CLI output is unchanged.
Port-forward sessions previously only bumped the workspace's last-used
time.
With the hidden `workspace-usage` experiment enabled, the server now
also records `port_forwarding` session counts under a new
`port_forwarding` family, which the deployment banner totals under
**Other**.
Without the experiment, `postWorkspaceUsage` returns 204 before reading
the body, so nothing changes.

<details>
<summary>Decisions</summary>

- Added `codersdk.UsageAppNamePortForwarding` (`port_forwarding`) rather
than reusing `ssh`, so port-forwarding isn't counted as interactive SSH.
The name matches the arbitrary app names RFC's connection-method name.
- Registered a `port_forwarding` family in `codersdk/appname.go`.
Families resolve at read time, so no data migration is needed. Template
insights list apps individually; telemetry, metricscache, and agentstats
gauges are legacy fixed fields and stay as they are. The Prometheus
insights family is left to #29906.
- Only TCP connections count. UDP forwards never see EOF, so one
datagram would keep the session active until exit.
- Reports once at startup, like the old call, then every minute and once
on shutdown. An idle tick sends an empty body, which still bumps
last-used.

</details>

Closes [CLI-31](https://linear.app/codercom/issue/CLI-31)

_This PR was generated by Coder Agents on behalf of @nickvigilante._


<details>
<summary>CI note: unrelated test-go-race-pg flake</summary>

The `test-go-race-pg` job failed on a data race between
`tailnet.(*configMaps).updatePeerLocked` and slog formatting of the same
peer value, which does not touch port-forward code. The job was rerun.

</details>
2026-10-02 11:05:48 -04:00

207 lines
8.0 KiB
Go

package codersdk
import (
"cmp"
"encoding/json"
"maps"
"slices"
"strings"
"unicode"
"github.com/google/uuid"
"golang.org/x/xerrors"
utilstrings "github.com/coder/coder/v2/coderd/util/strings"
)
// maxAppNameLength caps an app name in runes.
const maxAppNameLength = 64
// AppFamilyName is the bounded set of groups an app name falls into, such as
// vscode or ssh. A name Coder does not recognize falls under unknown.
type AppFamilyName string
const (
AppFamilyVSCode AppFamilyName = "vscode"
AppFamilyJetBrains AppFamilyName = "jetbrains"
AppFamilySSH AppFamilyName = "ssh"
AppFamilyReconnectingPTY AppFamilyName = "reconnecting_pty"
AppFamilyPortForwarding AppFamilyName = "port_forwarding"
// AppFamilySFTP only comes from history the sftp_mins column recorded.
AppFamilySFTP AppFamilyName = "sftp"
AppFamilyUnknown AppFamilyName = "unknown"
)
// AppNameOverflow sums the app names past the per-report cap.
const AppNameOverflow = "overflow"
// SessionCountApp is one app's session count and how to present it.
type SessionCountApp struct {
Count int64 `json:"count"`
// DisplayName is the registry's name for a known app, otherwise the
// normalized identifier itself.
DisplayName string `json:"display_name"`
// Icon is a bundled path under /icon/, empty if the app has none.
Icon string `json:"icon,omitempty"`
// Family is the group this app totals under.
Family AppFamilyName `json:"family"`
}
type sessionApp struct {
family AppFamilyName
displayName string
icon string
}
// sessionApps keys attribution and presentation by normalized registry module
// ID. An unregistered ID shows as-is under AppFamilyUnknown.
var sessionApps = map[string]sessionApp{
// VS Code forks report their URI scheme, with hyphens folded.
"vscode": {AppFamilyVSCode, "VS Code", "/icon/code.svg"},
"vscode_insiders": {AppFamilyVSCode, "VS Code Insiders", "/icon/code-insiders.svg"},
"vscode_web": {AppFamilyVSCode, "VS Code Web", "/icon/code.svg"},
"code_server": {AppFamilyVSCode, "code-server", "/icon/code.svg"},
"code_oss": {AppFamilyVSCode, "Code - OSS", ""},
"cursor": {AppFamilyVSCode, "Cursor", "/icon/cursor.svg"},
// Reported by Windsurf builds from before the Devin Desktop rename.
"windsurf": {AppFamilyVSCode, "Windsurf", "/icon/windsurf.svg"},
"positron": {AppFamilyVSCode, "Positron", "/icon/positron.svg"},
"vscodium": {AppFamilyVSCode, "VSCodium", ""},
"vscodium_insiders": {AppFamilyVSCode, "VSCodium Insiders", ""},
"codium": {AppFamilyVSCode, "VSCodium", ""},
"antigravity": {AppFamilyVSCode, "Antigravity", "/icon/antigravity.svg"},
"trae": {AppFamilyVSCode, "Trae", ""},
"trae_cn": {AppFamilyVSCode, "Trae CN", ""},
"kiro": {AppFamilyVSCode, "Kiro", "/icon/kiro.svg"},
"devin": {AppFamilyVSCode, "Devin Desktop", "/icon/devin.svg"},
"devin_next": {AppFamilyVSCode, "Devin Desktop Next", "/icon/devin.svg"},
"jetbrains": {AppFamilyJetBrains, "JetBrains", "/icon/jetbrains.svg"},
// JetBrains plugins report one name per IDE, whatever its edition.
"intellij": {AppFamilyJetBrains, "IntelliJ IDEA", "/icon/intellij.svg"},
"pycharm": {AppFamilyJetBrains, "PyCharm", "/icon/pycharm.svg"},
"goland": {AppFamilyJetBrains, "GoLand", "/icon/goland.svg"},
"webstorm": {AppFamilyJetBrains, "WebStorm", "/icon/webstorm.svg"},
"phpstorm": {AppFamilyJetBrains, "PhpStorm", "/icon/phpstorm.svg"},
"rubymine": {AppFamilyJetBrains, "RubyMine", "/icon/rubymine.svg"},
"clion": {AppFamilyJetBrains, "CLion", "/icon/clion.svg"},
"rider": {AppFamilyJetBrains, "Rider", "/icon/rider.svg"},
"rustrover": {AppFamilyJetBrains, "RustRover", "/icon/rustrover.svg"},
"datagrip": {AppFamilyJetBrains, "DataGrip", "/icon/datagrip.svg"},
"dataspell": {AppFamilyJetBrains, "DataSpell", "/icon/dataspell.svg"},
"mps": {AppFamilyJetBrains, "MPS", ""},
"android_studio": {AppFamilyJetBrains, "Android Studio", "/icon/android-studio.svg"},
// No agent reports sftp; the family covers the sftp_mins history.
"sftp": {AppFamilySFTP, "SFTP", "/icon/terminal.svg"},
// Zed speaks SSH, so it counts toward the SSH total.
"zed": {AppFamilySSH, "Zed", "/icon/zed.svg"},
"ssh": {AppFamilySSH, "SSH", "/icon/terminal.svg"},
"reconnecting_pty": {AppFamilyReconnectingPTY, "Web Terminal", ""},
"port_forwarding": {AppFamilyPortForwarding, "Port Forwarding", ""},
}
// SessionCountApps pairs each count with its presentation, keyed by app name.
func SessionCountApps(counts map[string]int64) map[string]SessionCountApp {
apps := make(map[string]SessionCountApp, len(counts))
for appName, count := range counts {
app := sessionApps[NormalizeAppName(appName)]
apps[appName] = SessionCountApp{
Count: count,
DisplayName: cmp.Or(app.displayName, appName),
Icon: app.icon,
Family: cmp.Or(app.family, AppFamilyUnknown),
}
}
return apps
}
// SessionCountAppFamilies returns a copy of the registry's app-to-family mapping.
func SessionCountAppFamilies() map[string]AppFamilyName {
families := make(map[string]AppFamilyName, len(sessionApps))
for appName, app := range sessionApps {
families[appName] = app.family
}
return families
}
// SumByFamily totals a per-app map by family. An unregistered name totals
// under AppFamilyUnknown.
func SumByFamily(byApp map[string]int64) map[AppFamilyName]int64 {
byFamily := make(map[AppFamilyName]int64)
for appName, value := range byApp {
byFamily[AppNameFamily(appName)] += value
}
return byFamily
}
// UnionByFamily folds per-app template IDs into the distinct set each family
// was seen in, ordered by app name.
func UnionByFamily(byApp map[string][]uuid.UUID) map[AppFamilyName][]uuid.UUID {
byFamily := make(map[AppFamilyName][]uuid.UUID, len(byApp))
seen := make(map[AppFamilyName]map[uuid.UUID]struct{}, len(byApp))
for _, appName := range slices.Sorted(maps.Keys(byApp)) {
family := AppNameFamily(appName)
if seen[family] == nil {
seen[family] = map[uuid.UUID]struct{}{}
}
for _, id := range byApp[appName] {
if _, ok := seen[family][id]; ok {
continue
}
seen[family][id] = struct{}{}
byFamily[family] = append(byFamily[family], id)
}
}
return byFamily
}
// AppNameFamily normalizes an app name and returns its family, or
// AppFamilyUnknown.
func AppNameFamily(appName string) AppFamilyName {
if app, ok := sessionApps[NormalizeAppName(appName)]; ok {
return app.family
}
return AppFamilyUnknown
}
// NormalizeAppName prepares a client-supplied app name for storage and
// lookup: it strips control characters, then trims, truncates, lowercases,
// and folds hyphens to underscores. Empty becomes AppFamilyUnknown.
// Stripping control characters covers both the null bytes Postgres TEXT
// rejects and escape sequences that would otherwise reach logs and terminals.
func NormalizeAppName(appName string) string {
appName = strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return -1
}
return r
}, appName)
// Trim before truncating so padding does not spend the budget, and after
// in case the cut lands in whitespace.
appName = strings.TrimSpace(appName)
appName = strings.TrimSpace(utilstrings.Truncate(appName, maxAppNameLength))
if appName == "" {
return string(AppFamilyUnknown)
}
return strings.ReplaceAll(strings.ToLower(appName), "-", "_")
}
// appMapValue is what an app-keyed JSONB payload holds.
type appMapValue interface {
int64 | []uuid.UUID
}
// DecodeAppMap decodes an app-keyed JSONB payload. An absent or SQL NULL
// payload decodes as empty; a malformed one errors rather than reading as zero.
func DecodeAppMap[V appMapValue](raw json.RawMessage) (map[string]V, error) {
var decoded map[string]V
if len(raw) > 0 {
if err := json.Unmarshal(raw, &decoded); err != nil {
return nil, xerrors.Errorf("unmarshal session app map: %w", err)
}
}
if decoded == nil {
decoded = map[string]V{}
}
return decoded, nil
}