Explorar o código

refactor(adapters): constants for PeerKind contract values

One place of truth for the PeerKind contract on each side: PeerKind* constants in adapters/types.go (replacing seven loose literals in live.go) and a mirror PeerKind map in the web app's routerExtras, used by the peer-label switch and PortPanel. Values and behaviour unchanged.

Refs #1546.
Nacho hai 1 mes
pai
achega
c501f75db8

+ 2 - 2
app/src/components/routers/PortPanel.tsx

@@ -5,7 +5,7 @@ import { Link } from 'react-router'
 import type { Router } from '@/data/mock'
 import type { WanInfo } from '@/data/types'
 import { SectionHeader } from '@/components/SectionHeader'
-import { getRouterExtras, portPeerDetail, portPeerLabel } from '@/components/routers/routerExtras'
+import { getRouterExtras, PeerKind, portPeerDetail, portPeerLabel } from '@/components/routers/routerExtras'
 import type { EthPort, RouterExtras, SfpInfo } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 import { Activity, ChevronDown, ChevronRight, Network } from 'lucide-react'
@@ -117,7 +117,7 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
                     const peer = portPeerLabel(port)
                     // #1040: agregación / switch inferido llevan icono de red:
                     // la app ADIVINA el par, no lo conoce.
-                    const inferred = (port.deviceCount ?? 0) > 0 || port.peerKind === 'inferred-switch'
+                    const inferred = (port.deviceCount ?? 0) > 0 || port.peerKind === PeerKind.InferredSwitch
                     const peerWithCue = inferred ? (
                       <span className="inline-flex max-w-full items-center gap-1">
                         <Network className="h-3 w-3 shrink-0 text-text-muted" strokeWidth={1.75} />

+ 22 - 8
app/src/components/routers/routerExtras.ts

@@ -99,6 +99,20 @@ export interface EthPort {
   health?: PortHealth // health score del puerto (#299)
 }
 
+/**
+ * Valores del contrato peerKind con el servidor (#1039). Espejo de las
+ * constantes PeerKind* de server-go/internal/adapters/types.go: un literal
+ * suelto aquí se queda sin actualizar cuando cambie el otro lado.
+ */
+export const PeerKind = {
+  RouterLink: 'router-link',
+  RouterLinkLldp: 'router-link-lldp',
+  ApWifi: 'ap-wifi',
+  Curated: 'curated',
+  Mac: 'mac',
+  InferredSwitch: 'inferred-switch',
+} as const
+
 /**
  * Etiqueta del par conectado a una boca. En agregación (deviceCount > 0)
  * el contador lo traduce la app con su i18n; el server ya no pre-formatea
@@ -110,12 +124,12 @@ export function portPeerLabel(port: EthPort): string {
     return i18n.t('routerDetail.ports.aggregation', { count: port.deviceCount })
   }
   switch (port.peerKind) {
-    case 'curated':
+    case PeerKind.Curated:
       // "nombre · detrás de <label de la boca>" traducido.
       return port.connectedTo
         ? `${port.connectedTo} · ${i18n.t('routerDetail.ports.behindLabel', { label: port.label })}`
         : ''
-    case 'inferred-switch':
+    case PeerKind.InferredSwitch:
       return i18n.t('routerDetail.ports.inferredSwitch')
     default:
       return port.connectedTo ?? ''
@@ -128,21 +142,21 @@ export function portPeerDetail(port: EthPort): string {
     return i18n.t('routerDetail.ports.aggregationHint')
   }
   switch (port.peerKind) {
-    case 'router-link':
-    case 'router-link-lldp':
+    case PeerKind.RouterLink:
+    case PeerKind.RouterLinkLldp:
       // #1150: la mgmt-ip del vecino LLDP viaja en detail y es más útil
       // que la plantilla; sin dato LLDP se queda la plantilla traducida.
       return (
         port.detail ||
-        i18n.t(port.peerKind === 'router-link' ? 'routerDetail.ports.detailRouterLink' : 'routerDetail.ports.detailRouterLinkLldp')
+        i18n.t(port.peerKind === PeerKind.RouterLink ? 'routerDetail.ports.detailRouterLink' : 'routerDetail.ports.detailRouterLinkLldp')
       )
-    case 'ap-wifi':
+    case PeerKind.ApWifi:
       return i18n.t('routerDetail.ports.detailApWifi')
-    case 'mac':
+    case PeerKind.Mac:
       return port.deviceMac
         ? i18n.t('routerDetail.ports.detailMac', { mac: port.deviceMac })
         : ''
-    case 'inferred-switch':
+    case PeerKind.InferredSwitch:
       return ''
     default:
       return port.detail ?? ''

+ 7 - 7
server-go/internal/adapters/live.go

@@ -5566,7 +5566,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 	if neighbor != "" {
 		port.ConnectedTo = d.routerByMac[neighbor]
 		// El cliente traduce la plantilla según PeerKind (#1039).
-		port.PeerKind = "router-link"
+		port.PeerKind = PeerKindRouterLink
 		// #1150: con switches encadenados la boca aprende las MACs de bridge
 		// de VARIAS unidades (el tráfico de sw2 atraviesa sw1) y la primera
 		// MAC ordenada puede nombrar al switch LEJANO. El LLDP anuncia al
@@ -5574,7 +5574,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 		// o su sysName manda sobre la MAC ordenada, y la mgmt-ip va al
 		// detalle del hover.
 		if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
-			port.PeerKind = "router-link-lldp"
+			port.PeerKind = PeerKindRouterLinkLLDP
 			if nb.ChassisMac != "" {
 				// La MAC del vecino (su bridge) va al hover como en las bocas
 				// de dispositivo único (#1150).
@@ -5603,7 +5603,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 			port.DeviceMac = all[0]
 			// La pista "cliente WiFi detrás" la traduce el cliente
 			// según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
-			port.PeerKind = "ap-wifi"
+			port.PeerKind = PeerKindAPWiFi
 			return port
 		}
 	}
@@ -5642,14 +5642,14 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 				// El cliente compone "nombre · detrás de <label>" con
 				// su i18n (#1039); aquí viaja el nombre a pelo.
 				port.ConnectedTo = name
-				port.PeerKind = "curated"
+				port.PeerKind = PeerKindCurated
 			} else if lldpName != "" {
 				// #931: sin nombre mejor, el equipo se anuncia por LLDP.
 				port.ConnectedTo = lldpName
-				port.PeerKind = "mac"
+				port.PeerKind = PeerKindMAC
 			} else {
 				port.ConnectedTo = port.Label
-				port.PeerKind = "mac"
+				port.PeerKind = PeerKindMAC
 			}
 			if lease, ok := d.leaseMap[mac]; ok && lease.IP != "" {
 				port.Detail = lease.IP
@@ -5733,7 +5733,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 		} else {
 			// Switch/bridge tonto inferido: sin lease ni alias que lo
 			// nombre. El cliente traduce la etiqueta (#1039/#1040).
-			port.PeerKind = "inferred-switch"
+			port.PeerKind = PeerKindInferredSwitch
 		}
 		return port
 	}

+ 13 - 2
server-go/internal/adapters/types.go

@@ -597,6 +597,18 @@ type SfpInfo struct {
 // EthPort es una boca ethernet ({id, label, up, speed?} + enriquecimiento de
 // vecino en el detalle: connectedTo/deviceMac/detail, SPEC §7.8 + contadores
 // por puerto #305: iface física, bytes/errores acumulados y rates + SFP #313).
+// PeerKind* son los valores del contrato PeerKind (EthPort) que el frontend
+// traduce (#1039). Un solo sitio de verdad: el consumidor TS los replica en
+// app/src/components/routers/routerExtras.ts.
+const (
+	PeerKindRouterLink     = "router-link"
+	PeerKindRouterLinkLLDP = "router-link-lldp"
+	PeerKindAPWiFi         = "ap-wifi"
+	PeerKindCurated        = "curated"
+	PeerKindMAC            = "mac"
+	PeerKindInferredSwitch = "inferred-switch"
+)
+
 type EthPort struct {
 	ID    string `json:"id"`
 	Label string `json:"label"`
@@ -622,8 +634,7 @@ type EthPort struct {
 	DeviceCount int `json:"deviceCount,omitempty"`
 	// PeerKind clasifica cómo se resolvió el par para que el CLIENTE
 	// traduzca las plantillas (#1039); "" = par nominal ya traducible tal
-	// cual (nombre/IP/alias). Valores: "router-link", "router-link-lldp",
-	// "ap-wifi", "curated", "inferred-switch".
+	// cual (nombre/IP/alias). Valores en las constantes PeerKind* de abajo.
 	PeerKind string `json:"peerKind,omitempty"`
 	Detail   string `json:"detail,omitempty"`
 	// Snmp indica que el puerto proviene de un switch gestionado por SNMP