store.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // store.go — capa de persistencia del rack canvas sobre SQLite. Funciones
  2. // a nivel de paquete tomando *sql.DB (mismo patrón que topooverride).
  3. //
  4. // SaveLayout es la única escritura de montajes: atómica y con validación
  5. // anti-solape server-side sobre el estado final (el cliente valida para el
  6. // snap; el servidor es la última frontera: dos montajes solapados en el
  7. // mismo rack nunca se persisten).
  8. package rack
  9. import (
  10. "crypto/rand"
  11. "database/sql"
  12. "encoding/hex"
  13. "encoding/json"
  14. "errors"
  15. "fmt"
  16. )
  17. // ErrOverlap indica que el estado final del layout tiene dos montajes
  18. // solapados o fuera de rack.
  19. var ErrOverlap = errors.New("rack: overlapping or out-of-rack mounts")
  20. // ErrPortBusy indica que el puerto ya tiene todos los cables que admite.
  21. var ErrPortBusy = errors.New("rack: port has no capacity for another cable")
  22. // ErrUnknownMount / ErrUnknownPort referencian montajes o puertos inexistentes.
  23. var ErrUnknownMount = errors.New("rack: montaje inexistente")
  24. // ErrUnknownPort indica un puerto que el dispositivo no declara en su perfil.
  25. var ErrUnknownPort = errors.New("rack: port not declared by the device")
  26. func newID() string {
  27. b := make([]byte, 8)
  28. _, _ = rand.Read(b)
  29. return hex.EncodeToString(b)
  30. }
  31. // --- Racks ---
  32. func ListRacks(db *sql.DB) ([]Rack, error) {
  33. rows, err := db.Query(`SELECT id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y
  34. FROM racks ORDER BY position_y, position_x, name`)
  35. if err != nil {
  36. return nil, err
  37. }
  38. defer rows.Close()
  39. out := []Rack{}
  40. for rows.Next() {
  41. var r Rack
  42. var loc sql.NullString
  43. if err := rows.Scan(&r.ID, &r.Name, &r.UHeight, &r.WidthStandard, &r.Numbering, &r.StyleJSON, &loc, &r.PositionX, &r.PositionY); err != nil {
  44. return nil, err
  45. }
  46. r.Location = loc.String
  47. out = append(out, r)
  48. }
  49. return out, rows.Err()
  50. }
  51. // GetRack devuelve sql.ErrNoRows si no existe.
  52. func GetRack(db *sql.DB, id string) (Rack, error) {
  53. var r Rack
  54. var loc sql.NullString
  55. err := db.QueryRow(`SELECT id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y
  56. FROM racks WHERE id = ?`, id).Scan(&r.ID, &r.Name, &r.UHeight, &r.WidthStandard, &r.Numbering, &r.StyleJSON, &loc, &r.PositionX, &r.PositionY)
  57. r.Location = loc.String
  58. return r, err
  59. }
  60. // CreateRack inserta un rack nuevo (id generado server-side) con defaults
  61. // aplicados y devuelve la fila creada.
  62. func CreateRack(db *sql.DB, in Rack) (Rack, error) {
  63. in.ID = newID()
  64. if in.WidthStandard == "" {
  65. in.WidthStandard = Width19
  66. }
  67. if in.Numbering == "" {
  68. in.Numbering = NumBottomUp
  69. }
  70. if in.StyleJSON == "" {
  71. in.StyleJSON = "{}"
  72. }
  73. if !in.Valid() {
  74. return Rack{}, fmt.Errorf("rack: invalid rack")
  75. }
  76. _, err := db.Exec(`INSERT INTO racks (id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y)
  77. VALUES (?, ?, ?, ?, ?, ?, NULLIF(?, ''), ?, ?)`,
  78. in.ID, in.Name, in.UHeight, in.WidthStandard, in.Numbering, in.StyleJSON, in.Location, in.PositionX, in.PositionY)
  79. return in, err
  80. }
  81. func UpdateRack(db *sql.DB, r Rack) error {
  82. if !r.Valid() {
  83. return fmt.Errorf("rack: invalid rack")
  84. }
  85. // Guarda: no reducir el rack por debajo de lo ya montado (la geometría
  86. // quedaría fuera del grid; el anti-solape se valida al guardar layouts).
  87. mounts, err := ListMountRowsByRack(db, r.ID)
  88. if err != nil {
  89. return err
  90. }
  91. for _, m := range mounts {
  92. if bottom := m.UStart + m.UHeight - 1; bottom > r.UHeight {
  93. return fmt.Errorf("%w: montaje %s ocupa hasta U%d (nuevo alto U%d)", ErrOverlap, m.ID, bottom, r.UHeight)
  94. }
  95. }
  96. res, err := db.Exec(`UPDATE racks SET name = ?, u_height = ?, width_standard = ?, numbering = ?, style_json = ?, location = NULLIF(?, ''), position_x = ?, position_y = ? WHERE id = ?`,
  97. r.Name, r.UHeight, r.WidthStandard, r.Numbering, r.StyleJSON, r.Location, r.PositionX, r.PositionY, r.ID)
  98. if err != nil {
  99. return err
  100. }
  101. return requireAffected(res)
  102. }
  103. // DeleteRack borra el rack; montajes y cables que cuelgan de ellos se van en
  104. // cascada (ON DELETE CASCADE).
  105. func DeleteRack(db *sql.DB, id string) error {
  106. res, err := db.Exec(`DELETE FROM racks WHERE id = ?`, id)
  107. if err != nil {
  108. return err
  109. }
  110. return requireAffected(res)
  111. }
  112. // --- Perfiles físicos de dispositivo ---
  113. func ListProfiles(db *sql.DB) ([]DeviceProfile, error) {
  114. rows, err := db.Query(`SELECT mac, faceplate_id, u_height, col_span, color, ports_json FROM device_rack_profile ORDER BY mac`)
  115. if err != nil {
  116. return nil, err
  117. }
  118. defer rows.Close()
  119. out := []DeviceProfile{}
  120. for rows.Next() {
  121. var p DeviceProfile
  122. var ports string
  123. if err := rows.Scan(&p.MAC, &p.FaceplateID, &p.UHeight, &p.ColSpan, &p.Color, &ports); err != nil {
  124. return nil, err
  125. }
  126. p.Ports = parsePorts(ports)
  127. out = append(out, p)
  128. }
  129. return out, rows.Err()
  130. }
  131. // GetProfile devuelve el perfil de una MAC; sql.ErrNoRows si no existe.
  132. func GetProfile(db *sql.DB, mac string) (DeviceProfile, error) {
  133. var p DeviceProfile
  134. var ports string
  135. err := db.QueryRow(`SELECT mac, faceplate_id, u_height, col_span, color, ports_json FROM device_rack_profile WHERE mac = ?`, mac).
  136. Scan(&p.MAC, &p.FaceplateID, &p.UHeight, &p.ColSpan, &p.Color, &ports)
  137. if err != nil {
  138. return DeviceProfile{}, err
  139. }
  140. p.Ports = parsePorts(ports)
  141. return p, nil
  142. }
  143. // UpsertProfile crea o actualiza el modelo físico del dispositivo.
  144. func UpsertProfile(db *sql.DB, p DeviceProfile) error {
  145. if p.MAC == "" {
  146. return fmt.Errorf("rack: mac requerida")
  147. }
  148. if p.UHeight < 1 {
  149. p.UHeight = 1
  150. }
  151. if p.ColSpan < 1 {
  152. p.ColSpan = RackColumns
  153. }
  154. ports, err := json.Marshal(p.Ports)
  155. if err != nil {
  156. return err
  157. }
  158. _, err = db.Exec(`INSERT INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json)
  159. VALUES (?, ?, ?, ?, ?, ?)
  160. ON CONFLICT(mac) DO UPDATE SET faceplate_id = excluded.faceplate_id, u_height = excluded.u_height,
  161. col_span = excluded.col_span, color = excluded.color, ports_json = excluded.ports_json`,
  162. p.MAC, p.FaceplateID, p.UHeight, p.ColSpan, p.Color, string(ports))
  163. return err
  164. }
  165. func parsePorts(s string) []Port {
  166. if s == "" {
  167. return []Port{}
  168. }
  169. var out []Port
  170. if err := json.Unmarshal([]byte(s), &out); err != nil {
  171. return []Port{}
  172. }
  173. if out == nil {
  174. out = []Port{}
  175. }
  176. return out
  177. }
  178. // --- Montajes ---
  179. // MountRow es un montaje con su huella resuelta (del perfil del dispositivo
  180. // o del catálogo de accesorios). Es lo que el canvas necesita para dibujar.
  181. type MountRow struct {
  182. Mount
  183. UHeight int
  184. ColSpan int
  185. }
  186. // Footprint devuelve la huella del montaje en el grid del rack.
  187. func (m MountRow) Footprint() Footprint {
  188. return Footprint{UStart: m.UStart, UHeight: m.UHeight, ColStart: m.ColStart, ColSpan: m.ColSpan}
  189. }
  190. // ListMountRows devuelve todos los montajes de todos los racks con huella
  191. // resuelta.
  192. func ListMountRows(db *sql.DB) ([]MountRow, error) {
  193. rows, err := db.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
  194. p.u_height, p.col_span
  195. FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
  196. ORDER BY m.rack_id, m.u_start DESC, m.col_start`)
  197. if err != nil {
  198. return nil, err
  199. }
  200. defer rows.Close()
  201. return scanMountRows(rows)
  202. }
  203. func ListMountRowsByRack(db *sql.DB, rackID string) ([]MountRow, error) {
  204. rows, err := db.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
  205. p.u_height, p.col_span
  206. FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
  207. WHERE m.rack_id = ?
  208. ORDER BY m.u_start DESC, m.col_start`, rackID)
  209. if err != nil {
  210. return nil, err
  211. }
  212. defer rows.Close()
  213. return scanMountRows(rows)
  214. }
  215. func scanMountRows(rows *sql.Rows) ([]MountRow, error) {
  216. out := []MountRow{}
  217. for rows.Next() {
  218. var m MountRow
  219. var devMAC, label sql.NullString
  220. var profU, profC sql.NullInt64
  221. if err := rows.Scan(&m.ID, &m.RackID, &devMAC, &m.FaceplateID, &m.UStart, &m.ColStart, &label, &m.StatusPin, &m.PortVisibility, &profU, &profC); err != nil {
  222. return nil, err
  223. }
  224. m.DeviceMAC = devMAC.String
  225. m.Label = label.String
  226. if m.DeviceMAC != "" {
  227. // Dispositivo: la huella la pone su perfil (la FK garantiza la
  228. // fila; el COALESCE es defensa ante bajas directas).
  229. m.UHeight, m.ColSpan = 1, RackColumns
  230. if profU.Valid {
  231. m.UHeight = int(profU.Int64)
  232. }
  233. if profC.Valid {
  234. m.ColSpan = int(profC.Int64)
  235. }
  236. } else {
  237. // Accesorio: la huella la pone el catálogo de faceplates.
  238. m.UHeight, m.ColSpan = AccessorySize(m.FaceplateID)
  239. }
  240. out = append(out, m)
  241. }
  242. return out, rows.Err()
  243. }
  244. // LayoutChange es una guardada atómica de montajes de un rack: altas/cambios
  245. // por upsert + bajas por id. Todos los upserted quedan en RackID (un layout
  246. // se guarda por rack; mover a OTRO rack es un SaveLayout de destino).
  247. type LayoutChange struct {
  248. RackID string
  249. Upsert []Mount
  250. Delete []string
  251. }
  252. // SaveLayout aplica el cambio en una transacción y valida el estado final:
  253. // cada montaje cabe en el rack y ningún par se solapa. Cualquier violación
  254. // revierte todo (ErrOverlap). Los montajes de dispositivo sin perfil crean
  255. // uno por defecto (1U x ancho completo) para satisfacer la FK.
  256. func SaveLayout(db *sql.DB, change LayoutChange) error {
  257. if change.RackID == "" {
  258. return fmt.Errorf("rack: rack_id requerido")
  259. }
  260. rack, err := GetRack(db, change.RackID)
  261. if err != nil {
  262. return err
  263. }
  264. tx, err := db.Begin()
  265. if err != nil {
  266. return err
  267. }
  268. defer tx.Rollback()
  269. for _, id := range change.Delete {
  270. if _, err := tx.Exec(`DELETE FROM rack_mounts WHERE id = ? AND rack_id = ?`, id, change.RackID); err != nil {
  271. return err
  272. }
  273. }
  274. for _, m := range change.Upsert {
  275. m.RackID = change.RackID
  276. if m.ID == "" {
  277. m.ID = newID()
  278. }
  279. if m.StatusPin == "" {
  280. m.StatusPin = StatusAuto
  281. }
  282. if m.PortVisibility == "" {
  283. m.PortVisibility = "auto"
  284. }
  285. if m.DeviceMAC != "" {
  286. // Perfil por defecto si el dispositivo aún no tiene: la FK lo exige.
  287. if _, err := tx.Exec(`INSERT INTO device_rack_profile (mac) VALUES (?) ON CONFLICT(mac) DO NOTHING`, m.DeviceMAC); err != nil {
  288. return err
  289. }
  290. }
  291. if _, err := tx.Exec(`INSERT INTO rack_mounts (id, rack_id, device_mac, faceplate_id, u_start, col_start, label, status_pin, port_visibility)
  292. VALUES (?, ?, NULLIF(?, ''), ?, ?, ?, NULLIF(?, ''), ?, ?)
  293. ON CONFLICT(id) DO UPDATE SET rack_id = excluded.rack_id, device_mac = excluded.device_mac, faceplate_id = excluded.faceplate_id,
  294. u_start = excluded.u_start, col_start = excluded.col_start, label = excluded.label,
  295. status_pin = excluded.status_pin, port_visibility = excluded.port_visibility`,
  296. m.ID, m.RackID, m.DeviceMAC, m.FaceplateID, m.UStart, m.ColStart, m.Label, m.StatusPin, m.PortVisibility); err != nil {
  297. return err
  298. }
  299. }
  300. // Validación del estado final: dentro de rack y sin solapes.
  301. final, err := listMountRowsTx(tx, change.RackID)
  302. if err != nil {
  303. return err
  304. }
  305. if err := validateLayout(rack.UHeight, final); err != nil {
  306. return err
  307. }
  308. return tx.Commit()
  309. }
  310. func listMountRowsTx(tx *sql.Tx, rackID string) ([]MountRow, error) {
  311. rows, err := tx.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
  312. p.u_height, p.col_span
  313. FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
  314. WHERE m.rack_id = ?
  315. ORDER BY m.u_start DESC, m.col_start`, rackID)
  316. if err != nil {
  317. return nil, err
  318. }
  319. defer rows.Close()
  320. return scanMountRows(rows)
  321. }
  322. // validateLayout comprueba que cada huella cabe en el rack y que ningún par
  323. // se solapa (O(n²) sobre ~docenas de montajes: sobra).
  324. func validateLayout(rackUHeight int, mounts []MountRow) error {
  325. footprints := make([]Footprint, 0, len(mounts))
  326. for _, m := range mounts {
  327. f := m.Footprint()
  328. if !FitsRack(rackUHeight, f) {
  329. return fmt.Errorf("%w: mount %s out of rack", ErrOverlap, m.ID)
  330. }
  331. footprints = append(footprints, f)
  332. }
  333. for i := range footprints {
  334. for j := i + 1; j < len(footprints); j++ {
  335. if Overlaps(footprints[i], footprints[j]) {
  336. return fmt.Errorf("%w: montajes %s y %s", ErrOverlap, mounts[i].ID, mounts[j].ID)
  337. }
  338. }
  339. }
  340. return nil
  341. }
  342. // --- Cables ---
  343. func ListCables(db *sql.DB) ([]Cable, error) {
  344. rows, err := db.Query(`SELECT id, from_mount, from_port, to_mount, to_port, type, label, properties_json, origin, created_at
  345. FROM rack_cables ORDER BY created_at`)
  346. if err != nil {
  347. return nil, err
  348. }
  349. defer rows.Close()
  350. out := []Cable{}
  351. for rows.Next() {
  352. var c Cable
  353. var label, props sql.NullString
  354. if err := rows.Scan(&c.ID, &c.FromMount, &c.FromPort, &c.ToMount, &c.ToPort, &c.Type, &label, &props, &c.Origin, &c.CreatedAt); err != nil {
  355. return nil, err
  356. }
  357. c.Label = label.String
  358. c.PropertiesJSON = props.String
  359. out = append(out, c)
  360. }
  361. return out, rows.Err()
  362. }
  363. // AddCable conecta dos puertos de dos montajes. Valida que los montajes
  364. // existan, que el puerto lo declare el dispositivo cuando su perfil tiene
  365. // puertos sembrados, y la capacidad del puerto: 1 cable (2 en pass-through
  366. // de patch panel).
  367. func AddCable(db *sql.DB, in Cable) (Cable, error) {
  368. if in.FromMount == "" || in.ToMount == "" || in.FromPort == "" || in.ToPort == "" {
  369. return Cable{}, fmt.Errorf("rack: from/to mount y port requeridos")
  370. }
  371. if in.Type == "" {
  372. in.Type = CableEthernet
  373. }
  374. if in.Origin == "" {
  375. in.Origin = OriginManual
  376. }
  377. if in.PropertiesJSON == "" {
  378. in.PropertiesJSON = "{}"
  379. }
  380. if in.ID == "" {
  381. in.ID = newID()
  382. }
  383. exists := func(id string) (bool, error) {
  384. var n int
  385. err := db.QueryRow(`SELECT COUNT(1) FROM rack_mounts WHERE id = ?`, id).Scan(&n)
  386. return n > 0, err
  387. }
  388. ok, err := exists(in.FromMount)
  389. if err != nil {
  390. return Cable{}, err
  391. }
  392. if !ok {
  393. return Cable{}, ErrUnknownMount
  394. }
  395. ok, err = exists(in.ToMount)
  396. if err != nil {
  397. return Cable{}, err
  398. }
  399. if !ok {
  400. return Cable{}, ErrUnknownMount
  401. }
  402. for _, end := range [][2]string{{in.FromMount, in.FromPort}, {in.ToMount, in.ToPort}} {
  403. if err := checkPortCapacity(db, end[0], end[1]); err != nil {
  404. return Cable{}, err
  405. }
  406. }
  407. _, err = db.Exec(`INSERT INTO rack_cables (id, from_mount, from_port, to_mount, to_port, type, label, properties_json, origin, created_at)
  408. VALUES (?, ?, ?, ?, ?, ?, ?, NULLIF(?, ''), ?, ?)`,
  409. in.ID, in.FromMount, in.FromPort, in.ToMount, in.ToPort, in.Type, in.Label, in.PropertiesJSON, in.Origin, in.CreatedAt)
  410. return in, err
  411. }
  412. func DeleteCable(db *sql.DB, id string) error {
  413. res, err := db.Exec(`DELETE FROM rack_cables WHERE id = ?`, id)
  414. if err != nil {
  415. return err
  416. }
  417. return requireAffected(res)
  418. }
  419. // checkPortCapacity valida que el puerto del montaje admita otro cable. Un
  420. // puerto normal admite exactamente 1; un puerto pass-through de patch panel
  421. // admite 2. Los dispositivos con puertos sembrados en su perfil rechazan IDs
  422. // de puerto que no declaren (los accesorios aún sin catálogo de puertos
  423. // aceptan cualquier ID).
  424. func checkPortCapacity(db *sql.DB, mountID, portID string) error {
  425. var deviceMAC, faceplate sql.NullString
  426. var ports string
  427. err := db.QueryRow(`SELECT device_mac, faceplate_id,
  428. COALESCE((SELECT ports_json FROM device_rack_profile p WHERE p.mac = m.device_mac), '')
  429. FROM rack_mounts m WHERE m.id = ?`, mountID).Scan(&deviceMAC, &faceplate, &ports)
  430. if err == sql.ErrNoRows {
  431. return ErrUnknownMount
  432. }
  433. if err != nil {
  434. return err
  435. }
  436. if deviceMAC.Valid {
  437. declared := parsePorts(ports)
  438. if len(declared) > 0 {
  439. found := false
  440. for _, p := range declared {
  441. if p.ID == portID {
  442. found = true
  443. break
  444. }
  445. }
  446. if !found {
  447. return fmt.Errorf("%w: %s", ErrUnknownPort, portID)
  448. }
  449. }
  450. }
  451. capacity := 1
  452. if faceplate.Valid && IsPassThrough(faceplate.String) {
  453. capacity = 2
  454. }
  455. var n int
  456. if err := db.QueryRow(`SELECT COUNT(1) FROM rack_cables
  457. WHERE (from_mount = ? AND from_port = ?) OR (to_mount = ? AND to_port = ?)`,
  458. mountID, portID, mountID, portID).Scan(&n); err != nil {
  459. return err
  460. }
  461. if n+1 > capacity {
  462. return fmt.Errorf("%w: %s/%s", ErrPortBusy, mountID, portID)
  463. }
  464. return nil
  465. }
  466. func requireAffected(res sql.Result) error {
  467. n, err := res.RowsAffected()
  468. if err != nil {
  469. return err
  470. }
  471. if n == 0 {
  472. return sql.ErrNoRows
  473. }
  474. return nil
  475. }