Put a link on standby; the routing metric stays per city pair (#122)

A backup-only link next to a normal one still carried traffic, because
parallel links merge into one edge. The metric stays on the city pair
(S.pairMet), and any link can go on standby: it adds capacity that
fills only after the active links, so it idles as a backup, takes the
overflow when they are full and carries the traffic when they are down.
Build order no longer matters, and adding a link never idles the
others. Old saves keep each pair's lowest metric with every link
active, which is how they routed before. The panel says what a standby
link is doing, the redundancy list tags it, the map draws it dashed
while idle, and traceroute shows the active link.
This commit is contained in:
Frederic Jung 2026-10-28 06:54:11 +01:00
parent da69c5d843
commit b4f8d9c7f5
18 changed files with 217 additions and 18 deletions

View file

@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows
## [Unreleased] ## [Unreleased]
- You can put a link on standby, so one of two links between the same cities sits idle as a backup (#122). It carries traffic only when the other links are full or down, so its capacity is never wasted, and the map draws it dashed while it waits. The routing metric still applies to every link between the two cities.
## [1.35.1] — 2026-10-28 ## [1.35.1] — 2026-10-28
- Subsea cables stay at sea: Pacific cables no longer draw a line across the whole world where the map wraps round (#183), and over 170 cable routes that cut across Africa, Arabia, India, Brazil and other coasts now follow the sea. Cables into inland cities like Paris, Dublin and Hong Kong come ashore at the nearest coast. - Subsea cables stay at sea: Pacific cables no longer draw a line across the whole world where the map wraps round (#183), and over 170 cable routes that cut across Africa, Arabia, India, Brazil and other coasts now follow the sea. Cables into inland cities like Paris, Dublin and Hong Kong come ashore at the nearest coast.

View file

@ -106,8 +106,10 @@ never freezes the game.
## compute(): the traffic model ## compute(): the traffic model
1. Builds a graph from your live links: parallel links between the same two cities 1. Builds a graph from your live links: parallel links between the same two cities
merge into one edge with summed capacity. Link metrics set weights; Dijkstra gives merge into one edge with summed capacity. The routing metric belongs to the city pair
shortest paths from each POP. (`S.pairMet`) and sets the edge's weight; Dijkstra gives shortest paths from each POP.
Links on standby (`l.standby`) add their capacity to the edge, but when loads are
handed back to links the active ones fill first and standby links take the rest.
2. Builds the exit list `E`: embedded caches (rank 0), PNIs (1), IX ports (2), 2. Builds the exit list `E`: embedded caches (rank 0), PNIs (1), IX ports (2),
transit (3). Each exit has a capacity, the networks it can reach (`ok(net)`) and an transit (3). Each exit has a capacity, the networks it can reach (`ok(net)`) and an
egress preference (`high`, `normal`, `low` = backup only). egress preference (`high`, `normal`, `low` = backup only).

View file

@ -1249,6 +1249,7 @@
"common.spreadsheet_ipam":"IPAM en hoja de cálculo", "common.spreadsheet_ipam":"IPAM en hoja de cálculo",
"common.stage_six":"Fase seis", "common.stage_six":"Fase seis",
"common.standard":"Estándar", "common.standard":"Estándar",
"common.standby":"En espera",
"common.start_a_new_network":"Empezar una red nueva", "common.start_a_new_network":"Empezar una red nueva",
"common.start_building":"Empezar a construir", "common.start_building":"Empezar a construir",
"common.start_construction":"Empezar la construcción", "common.start_construction":"Empezar la construcción",
@ -2092,6 +2093,7 @@
"link_modal.waves_on_the_same_route_share":"Las ondas de la misma ruta comparten su suerte: una retroexcavadora las corta todas.", "link_modal.waves_on_the_same_route_share":"Las ondas de la misma ruta comparten su suerte: una retroexcavadora las corta todas.",
"link_modal.you_already_have_n_link_here":{"one":"Ya tienes {n} enlace aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?","other":"Ya tienes {n} enlaces aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?"}, "link_modal.you_already_have_n_link_here":{"one":"Ya tienes {n} enlace aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?","other":"Ya tienes {n} enlaces aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?"},
"link_panels.a_bigger_fabric_carries_more_traffic":"Una fabric mayor transporta más tráfico y tiene sitio para más miembros. Tu router de aquí aún tiene que aguantar el ritmo.", "link_panels.a_bigger_fabric_carries_more_traffic":"Una fabric mayor transporta más tráfico y tiene sitio para más miembros. Tu router de aquí aún tiene que aguantar el ritmo.",
"link_panels.a_link_on_standby_carries_traffic":"Un enlace en espera solo lleva tráfico cuando los demás enlaces entre estas ciudades están llenos o caídos.",
"link_panels.a_regen_site_turns_the_light":"Un sitio regenerador convierte la luz de nuevo en bits a mitad de camino y la envía renovada, así que las ópticas solo tienen que llegar al siguiente sitio. Cada uno necesita una tarjeta regeneradora por cada canal iluminado. {price}/mes por sitio por la caseta.", "link_panels.a_regen_site_turns_the_light":"Un sitio regenerador convierte la luz de nuevo en bits a mitad de camino y la envía renovada, así que las ópticas solo tienen que llegar al siguiente sitio. Cada uno necesita una tarjeta regeneradora por cada canal iluminado. {price}/mes por sitio por la caseta.",
"link_panels.abandon_the_fiber":"Abandonar la fibra", "link_panels.abandon_the_fiber":"Abandonar la fibra",
"link_panels.add_parallel_link":"Añadir enlace paralelo", "link_panels.add_parallel_link":"Añadir enlace paralelo",
@ -2151,6 +2153,9 @@
"link_panels.not_present_in_any_of_your":"Aún no está presente en ninguna de tus ciudades", "link_panels.not_present_in_any_of_your":"Aún no está presente en ninguna de tus ciudades",
"link_panels.nothing_spare_to_sell_on_this":"Ahora mismo no queda nada que vender en esta fibra.", "link_panels.nothing_spare_to_sell_on_this":"Ahora mismo no queda nada que vender en esta fibra.",
"link_panels.off_while_your_peering_policy_is":"Desactivado mientras tu política de peering sea {pol}", "link_panels.off_while_your_peering_policy_is":"Desactivado mientras tu política de peering sea {pol}",
"link_panels.on_standby_but_carrying_the_traffic":"En espera, pero lleva el tráfico: ningún enlace activo entre estas ciudades funciona.",
"link_panels.on_standby_idle_while_the_other":"En espera: inactivo mientras los demás enlaces entre estas ciudades tengan sitio.",
"link_panels.on_standby_taking_the_overflow":"En espera: lleva el desbordamiento, porque los demás enlaces entre estas ciudades están llenos.",
"link_panels.open_peer_but_not_on_any":"Open peer, pero no en ningún IX donde tengas POP. Más cercano: {city}", "link_panels.open_peer_but_not_on_any":"Open peer, pero no en ningún IX donde tengas POP. Más cercano: {city}",
"link_panels.open_peer_but_not_on_any_bfbb":"Open peer, pero no en ningún IX donde tengas POP", "link_panels.open_peer_but_not_on_any_bfbb":"Open peer, pero no en ningún IX donde tengas POP",
"link_panels.open_peer_join_the_route_server":"Open peer: únete al route server de {ix}", "link_panels.open_peer_join_the_route_server":"Open peer: únete al route server de {ix}",
@ -2168,6 +2173,7 @@
"link_panels.ports_at_p_of_the_usual":"Puertos al {p} % del precio habitual.", "link_panels.ports_at_p_of_the_usual":"Puertos al {p} % del precio habitual.",
"link_panels.ports_up_to_port_are_free":"Los puertos hasta {port} son gratis.", "link_panels.ports_up_to_port_are_free":"Los puertos hasta {port} son gratis.",
"link_panels.price_n_days":"{price} · {n} días", "link_panels.price_n_days":"{price} · {n} días",
"link_panels.put_this_link_on_standby":"Poner este enlace en espera",
"link_panels.ready_for_a_pni_in_city":"Listo para un PNI en {city}", "link_panels.ready_for_a_pni_in_city":"Listo para un PNI en {city}",
"link_panels.ready_in_n_days":"Listo en {n} días", "link_panels.ready_in_n_days":"Listo en {n} días",
"link_panels.really_give_it_up":"¿Renunciar de verdad?", "link_panels.really_give_it_up":"¿Renunciar de verdad?",
@ -2190,6 +2196,7 @@
"link_panels.spares_kit_on":"Kit de repuestos activo ✓", "link_panels.spares_kit_on":"Kit de repuestos activo ✓",
"link_panels.stock_a_spare_optic_price":"Tener una {optic} de repuesto <small>{price}</small>", "link_panels.stock_a_spare_optic_price":"Tener una {optic} de repuesto <small>{price}</small>",
"link_panels.sys_level_n":"{sys} <small>nivel {n}</small>", "link_panels.sys_level_n":"{sys} <small>nivel {n}</small>",
"link_panels.take_it_off_standby":"Sacarlo de la espera",
"link_panels.there_s_no_ix_in_city":"Aún no hay IX en {city}. Funda uno: las redes se unen con el tiempo, te pagan por los puertos y hacen peering contigo gratis.", "link_panels.there_s_no_ix_in_city":"Aún no hay IX en {city}. Funda uno: las redes se unen con el tiempo, te pagan por los puertos y hacen peering contigo gratis.",
"link_panels.they_need_the_full_internet_your":"Necesitan todo internet. Tu alcance es del {pct}.", "link_panels.they_need_the_full_internet_your":"Necesitan todo internet. Tu alcance es del {pct}.",
"link_panels.this_fiber_is_dark_add_optics":"Esta fibra está a oscuras. Añade ópticas abajo para transportar tráfico.", "link_panels.this_fiber_is_dark_add_optics":"Esta fibra está a oscuras. Añade ópticas abajo para transportar tráfico.",

View file

@ -1249,6 +1249,7 @@
"common.spreadsheet_ipam":"IPAM sur tableur", "common.spreadsheet_ipam":"IPAM sur tableur",
"common.stage_six":"Stade six", "common.stage_six":"Stade six",
"common.standard":"Standard", "common.standard":"Standard",
"common.standby":"En attente",
"common.start_a_new_network":"Créer un nouveau réseau", "common.start_a_new_network":"Créer un nouveau réseau",
"common.start_building":"Commencer à construire", "common.start_building":"Commencer à construire",
"common.start_construction":"Lancer les travaux", "common.start_construction":"Lancer les travaux",
@ -2092,6 +2093,7 @@
"link_modal.waves_on_the_same_route_share":"Les longueurs d’onde d’un même parcours partagent son sort : une pelleteuse les coupe toutes.", "link_modal.waves_on_the_same_route_share":"Les longueurs d’onde d’un même parcours partagent son sort : une pelleteuse les coupe toutes.",
"link_modal.you_already_have_n_link_here":{"one":"Tu as déjà {n} lien ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?","other":"Tu as déjà {n} liens ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?"}, "link_modal.you_already_have_n_link_here":{"one":"Tu as déjà {n} lien ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?","other":"Tu as déjà {n} liens ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?"},
"link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric plus gros transporte plus de trafic et accueille plus de membres. Ton routeur ici doit quand même suivre.", "link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric plus gros transporte plus de trafic et accueille plus de membres. Ton routeur ici doit quand même suivre.",
"link_panels.a_link_on_standby_carries_traffic":"Un lien en attente ne porte du trafic que lorsque les autres liens entre ces villes sont pleins ou coupés.",
"link_panels.a_regen_site_turns_the_light":"Un site de régénération reconvertit la lumière en bits à mi-chemin et la renvoie toute fraîche, donc les optiques n’ont qu’à atteindre le site suivant. Chacun demande une carte de régénération par canal allumé. {price}/mois par site pour l’abri.", "link_panels.a_regen_site_turns_the_light":"Un site de régénération reconvertit la lumière en bits à mi-chemin et la renvoie toute fraîche, donc les optiques n’ont qu’à atteindre le site suivant. Chacun demande une carte de régénération par canal allumé. {price}/mois par site pour l’abri.",
"link_panels.abandon_the_fiber":"Abandonner la fibre", "link_panels.abandon_the_fiber":"Abandonner la fibre",
"link_panels.add_parallel_link":"Ajouter un lien parallèle", "link_panels.add_parallel_link":"Ajouter un lien parallèle",
@ -2151,6 +2153,9 @@
"link_panels.not_present_in_any_of_your":"Pas encore présent dans tes villes", "link_panels.not_present_in_any_of_your":"Pas encore présent dans tes villes",
"link_panels.nothing_spare_to_sell_on_this":"Rien à vendre sur cette fibre pour l’instant.", "link_panels.nothing_spare_to_sell_on_this":"Rien à vendre sur cette fibre pour l’instant.",
"link_panels.off_while_your_peering_policy_is":"Désactivé tant que votre politique de peering est {pol}", "link_panels.off_while_your_peering_policy_is":"Désactivé tant que votre politique de peering est {pol}",
"link_panels.on_standby_but_carrying_the_traffic":"En attente, mais il porte le trafic : aucun lien actif entre ces villes ne fonctionne.",
"link_panels.on_standby_idle_while_the_other":"En attente : au repos tant que les autres liens entre ces villes ont de la place.",
"link_panels.on_standby_taking_the_overflow":"En attente : il prend le débordement, car les autres liens entre ces villes sont pleins.",
"link_panels.open_peer_but_not_on_any":"Peer ouvert, mais sur aucun IX où tu as un POP. Le plus proche : {city}", "link_panels.open_peer_but_not_on_any":"Peer ouvert, mais sur aucun IX où tu as un POP. Le plus proche : {city}",
"link_panels.open_peer_but_not_on_any_bfbb":"Peer ouvert, mais sur aucun IX où tu as un POP", "link_panels.open_peer_but_not_on_any_bfbb":"Peer ouvert, mais sur aucun IX où tu as un POP",
"link_panels.open_peer_join_the_route_server":"Peer ouvert : rejoins le route server de {ix}", "link_panels.open_peer_join_the_route_server":"Peer ouvert : rejoins le route server de {ix}",
@ -2168,6 +2173,7 @@
"link_panels.ports_at_p_of_the_usual":"Ports à {p} % du prix habituel.", "link_panels.ports_at_p_of_the_usual":"Ports à {p} % du prix habituel.",
"link_panels.ports_up_to_port_are_free":"Les ports jusqu’à {port} sont gratuits.", "link_panels.ports_up_to_port_are_free":"Les ports jusqu’à {port} sont gratuits.",
"link_panels.price_n_days":"{price} · {n} jours", "link_panels.price_n_days":"{price} · {n} jours",
"link_panels.put_this_link_on_standby":"Mettre ce lien en attente",
"link_panels.ready_for_a_pni_in_city":"Prêt pour un PNI à {city}", "link_panels.ready_for_a_pni_in_city":"Prêt pour un PNI à {city}",
"link_panels.ready_in_n_days":"Prêt dans {n} jours", "link_panels.ready_in_n_days":"Prêt dans {n} jours",
"link_panels.really_give_it_up":"Vraiment y renoncer ?", "link_panels.really_give_it_up":"Vraiment y renoncer ?",
@ -2190,6 +2196,7 @@
"link_panels.spares_kit_on":"Kit de rechange actif ✓", "link_panels.spares_kit_on":"Kit de rechange actif ✓",
"link_panels.stock_a_spare_optic_price":"Stocker un {optic} de rechange <small>{price}</small>", "link_panels.stock_a_spare_optic_price":"Stocker un {optic} de rechange <small>{price}</small>",
"link_panels.sys_level_n":"{sys} <small>niveau {n}</small>", "link_panels.sys_level_n":"{sys} <small>niveau {n}</small>",
"link_panels.take_it_off_standby":"Le sortir de l’attente",
"link_panels.there_s_no_ix_in_city":"Pas encore d’IX à {city}. Fondes-en un : les réseaux te rejoignent peu à peu, te paient leurs ports et font du peering gratuit avec toi.", "link_panels.there_s_no_ix_in_city":"Pas encore d’IX à {city}. Fondes-en un : les réseaux te rejoignent peu à peu, te paient leurs ports et font du peering gratuit avec toi.",
"link_panels.they_need_the_full_internet_your":"Ils veulent tout Internet. Ta couverture est de {pct}.", "link_panels.they_need_the_full_internet_your":"Ils veulent tout Internet. Ta couverture est de {pct}.",
"link_panels.this_fiber_is_dark_add_optics":"Cette fibre est éteinte. Ajoute des optiques ci-dessous pour transporter du trafic.", "link_panels.this_fiber_is_dark_add_optics":"Cette fibre est éteinte. Ajoute des optiques ci-dessous pour transporter du trafic.",

View file

@ -1249,6 +1249,7 @@
"common.spreadsheet_ipam":"IPAM su foglio di calcolo", "common.spreadsheet_ipam":"IPAM su foglio di calcolo",
"common.stage_six":"Fase sei", "common.stage_six":"Fase sei",
"common.standard":"Standard", "common.standard":"Standard",
"common.standby":"Standby",
"common.start_a_new_network":"Crea una nuova rete", "common.start_a_new_network":"Crea una nuova rete",
"common.start_building":"Inizia a costruire", "common.start_building":"Inizia a costruire",
"common.start_construction":"Avvia i lavori", "common.start_construction":"Avvia i lavori",
@ -2092,6 +2093,7 @@
"link_modal.waves_on_the_same_route_share":"Le wave sullo stesso percorso ne condividono la sorte: una ruspa le taglia tutte.", "link_modal.waves_on_the_same_route_share":"Le wave sullo stesso percorso ne condividono la sorte: una ruspa le taglia tutte.",
"link_modal.you_already_have_n_link_here":{"one":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?","other":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?"}, "link_modal.you_already_have_n_link_here":{"one":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?","other":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?"},
"link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric più grande porta più traffico e ha posto per più membri. Il tuo router qui deve comunque starci dietro.", "link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric più grande porta più traffico e ha posto per più membri. Il tuo router qui deve comunque starci dietro.",
"link_panels.a_link_on_standby_carries_traffic":"Un link in standby porta traffico solo quando gli altri link tra queste città sono pieni o giù.",
"link_panels.a_regen_site_turns_the_light":"Un sito di rigenerazione riconverte la luce in bit a metà strada e la rimanda fresca, così le ottiche devono arrivare solo al sito successivo. Ognuno richiede una scheda di rigenerazione per ogni canale acceso. {price}/mese a sito per la casupola.", "link_panels.a_regen_site_turns_the_light":"Un sito di rigenerazione riconverte la luce in bit a metà strada e la rimanda fresca, così le ottiche devono arrivare solo al sito successivo. Ognuno richiede una scheda di rigenerazione per ogni canale acceso. {price}/mese a sito per la casupola.",
"link_panels.abandon_the_fiber":"Abbandona la fibra", "link_panels.abandon_the_fiber":"Abbandona la fibra",
"link_panels.add_parallel_link":"Aggiungi link parallelo", "link_panels.add_parallel_link":"Aggiungi link parallelo",
@ -2151,6 +2153,9 @@
"link_panels.not_present_in_any_of_your":"Non è ancora presente in nessuna delle tue città", "link_panels.not_present_in_any_of_your":"Non è ancora presente in nessuna delle tue città",
"link_panels.nothing_spare_to_sell_on_this":"Per ora non c’è niente da vendere su questa fibra.", "link_panels.nothing_spare_to_sell_on_this":"Per ora non c’è niente da vendere su questa fibra.",
"link_panels.off_while_your_peering_policy_is":"Spento finché la tua politica di peering è {pol}", "link_panels.off_while_your_peering_policy_is":"Spento finché la tua politica di peering è {pol}",
"link_panels.on_standby_but_carrying_the_traffic":"In standby, ma porta il traffico: nessun link attivo tra queste città funziona.",
"link_panels.on_standby_idle_while_the_other":"In standby: a riposo finché gli altri link tra queste città hanno spazio.",
"link_panels.on_standby_taking_the_overflow":"In standby: prende il traffico in eccesso, perché gli altri link tra queste città sono pieni.",
"link_panels.open_peer_but_not_on_any":"Peer aperto, ma non su nessun IX dove hai un POP. Il più vicino: {city}", "link_panels.open_peer_but_not_on_any":"Peer aperto, ma non su nessun IX dove hai un POP. Il più vicino: {city}",
"link_panels.open_peer_but_not_on_any_bfbb":"Peer aperto, ma non su nessun IX dove hai un POP", "link_panels.open_peer_but_not_on_any_bfbb":"Peer aperto, ma non su nessun IX dove hai un POP",
"link_panels.open_peer_join_the_route_server":"Peer aperto: entra nel route server di {ix}", "link_panels.open_peer_join_the_route_server":"Peer aperto: entra nel route server di {ix}",
@ -2168,6 +2173,7 @@
"link_panels.ports_at_p_of_the_usual":"Porte al {p}% del prezzo normale.", "link_panels.ports_at_p_of_the_usual":"Porte al {p}% del prezzo normale.",
"link_panels.ports_up_to_port_are_free":"Le porte fino a {port} sono gratis.", "link_panels.ports_up_to_port_are_free":"Le porte fino a {port} sono gratis.",
"link_panels.price_n_days":"{price} · {n} giorni", "link_panels.price_n_days":"{price} · {n} giorni",
"link_panels.put_this_link_on_standby":"Metti questo link in standby",
"link_panels.ready_for_a_pni_in_city":"Pronto per un PNI a {city}", "link_panels.ready_for_a_pni_in_city":"Pronto per un PNI a {city}",
"link_panels.ready_in_n_days":"Pronto tra {n} giorni", "link_panels.ready_in_n_days":"Pronto tra {n} giorni",
"link_panels.really_give_it_up":"Rinunciare davvero?", "link_panels.really_give_it_up":"Rinunciare davvero?",
@ -2190,6 +2196,7 @@
"link_panels.spares_kit_on":"Kit ricambi attivo ✓", "link_panels.spares_kit_on":"Kit ricambi attivo ✓",
"link_panels.stock_a_spare_optic_price":"Metti da parte un {optic} di scorta <small>{price}</small>", "link_panels.stock_a_spare_optic_price":"Metti da parte un {optic} di scorta <small>{price}</small>",
"link_panels.sys_level_n":"{sys} <small>livello {n}</small>", "link_panels.sys_level_n":"{sys} <small>livello {n}</small>",
"link_panels.take_it_off_standby":"Toglilo dallo standby",
"link_panels.there_s_no_ix_in_city":"A {city} non c’è ancora un IX. Fondane uno: le reti si uniscono col tempo, ti pagano le porte e fanno peering con te gratis.", "link_panels.there_s_no_ix_in_city":"A {city} non c’è ancora un IX. Fondane uno: le reti si uniscono col tempo, ti pagano le porte e fanno peering con te gratis.",
"link_panels.they_need_the_full_internet_your":"Vogliono internet per intero. La tua copertura è del {pct}.", "link_panels.they_need_the_full_internet_your":"Vogliono internet per intero. La tua copertura è del {pct}.",
"link_panels.this_fiber_is_dark_add_optics":"Questa fibra è spenta. Aggiungi le ottiche qui sotto per trasportare traffico.", "link_panels.this_fiber_is_dark_add_optics":"Questa fibra è spenta. Aggiungi le ottiche qui sotto per trasportare traffico.",

View file

@ -1249,6 +1249,7 @@
"common.spreadsheet_ipam":"IPAM em planilha", "common.spreadsheet_ipam":"IPAM em planilha",
"common.stage_six":"Estágio seis", "common.stage_six":"Estágio seis",
"common.standard":"Padrão", "common.standard":"Padrão",
"common.standby":"Reserva",
"common.start_a_new_network":"Começar uma nova rede", "common.start_a_new_network":"Começar uma nova rede",
"common.start_building":"Começar a construir", "common.start_building":"Começar a construir",
"common.start_construction":"Iniciar obra", "common.start_construction":"Iniciar obra",
@ -2092,6 +2093,7 @@
"link_modal.waves_on_the_same_route_share":"Waves na mesma rota compartilham o destino: uma retroescavadeira corta todas.", "link_modal.waves_on_the_same_route_share":"Waves na mesma rota compartilham o destino: uma retroescavadeira corta todas.",
"link_modal.you_already_have_n_link_here":{"one":"Você já tem {n} link aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?","other":"Você já tem {n} links aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?"}, "link_modal.you_already_have_n_link_here":{"one":"Você já tem {n} link aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?","other":"Você já tem {n} links aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?"},
"link_panels.a_bigger_fabric_carries_more_traffic":"Um fabric maior carrega mais tráfego e tem espaço para mais membros. Seu router aqui ainda precisa dar conta.", "link_panels.a_bigger_fabric_carries_more_traffic":"Um fabric maior carrega mais tráfego e tem espaço para mais membros. Seu router aqui ainda precisa dar conta.",
"link_panels.a_link_on_standby_carries_traffic":"Um link de reserva só leva tráfego quando os outros links entre estas cidades estão cheios ou fora do ar.",
"link_panels.a_regen_site_turns_the_light":"Um site de regeneração transforma a luz de volta em bits no meio do caminho e a reenvia novinha, então as ópticas só precisam alcançar o próximo site. Cada um precisa de uma placa de regeneração para cada canal aceso. {price}/mês por site pelo abrigo.", "link_panels.a_regen_site_turns_the_light":"Um site de regeneração transforma a luz de volta em bits no meio do caminho e a reenvia novinha, então as ópticas só precisam alcançar o próximo site. Cada um precisa de uma placa de regeneração para cada canal aceso. {price}/mês por site pelo abrigo.",
"link_panels.abandon_the_fiber":"Abandonar a fibra", "link_panels.abandon_the_fiber":"Abandonar a fibra",
"link_panels.add_parallel_link":"Adicionar link paralelo", "link_panels.add_parallel_link":"Adicionar link paralelo",
@ -2151,6 +2153,9 @@
"link_panels.not_present_in_any_of_your":"Ainda não está em nenhuma das suas cidades", "link_panels.not_present_in_any_of_your":"Ainda não está em nenhuma das suas cidades",
"link_panels.nothing_spare_to_sell_on_this":"Nada sobrando para vender nesta fibra por enquanto.", "link_panels.nothing_spare_to_sell_on_this":"Nada sobrando para vender nesta fibra por enquanto.",
"link_panels.off_while_your_peering_policy_is":"Desligado enquanto sua política de peering for {pol}", "link_panels.off_while_your_peering_policy_is":"Desligado enquanto sua política de peering for {pol}",
"link_panels.on_standby_but_carrying_the_traffic":"De reserva, mas levando o tráfego: nenhum link ativo entre estas cidades está no ar.",
"link_panels.on_standby_idle_while_the_other":"De reserva: ocioso enquanto os outros links entre estas cidades tiverem espaço.",
"link_panels.on_standby_taking_the_overflow":"De reserva: levando o excedente, porque os outros links entre estas cidades estão cheios.",
"link_panels.open_peer_but_not_on_any":"Peer aberto, mas em nenhum IX onde você tem POP. O mais próximo: {city}", "link_panels.open_peer_but_not_on_any":"Peer aberto, mas em nenhum IX onde você tem POP. O mais próximo: {city}",
"link_panels.open_peer_but_not_on_any_bfbb":"Peer aberto, mas em nenhum IX onde você tem POP", "link_panels.open_peer_but_not_on_any_bfbb":"Peer aberto, mas em nenhum IX onde você tem POP",
"link_panels.open_peer_join_the_route_server":"Peer aberto: entre no route server do {ix}", "link_panels.open_peer_join_the_route_server":"Peer aberto: entre no route server do {ix}",
@ -2168,6 +2173,7 @@
"link_panels.ports_at_p_of_the_usual":"Portas a {p}% do preço normal.", "link_panels.ports_at_p_of_the_usual":"Portas a {p}% do preço normal.",
"link_panels.ports_up_to_port_are_free":"Portas até {port} são grátis.", "link_panels.ports_up_to_port_are_free":"Portas até {port} são grátis.",
"link_panels.price_n_days":"{price} · {n} dias", "link_panels.price_n_days":"{price} · {n} dias",
"link_panels.put_this_link_on_standby":"Deixar este link de reserva",
"link_panels.ready_for_a_pni_in_city":"Pronto para um PNI em {city}", "link_panels.ready_for_a_pni_in_city":"Pronto para um PNI em {city}",
"link_panels.ready_in_n_days":"Pronto em {n} dias", "link_panels.ready_in_n_days":"Pronto em {n} dias",
"link_panels.really_give_it_up":"Desistir mesmo?", "link_panels.really_give_it_up":"Desistir mesmo?",
@ -2190,6 +2196,7 @@
"link_panels.spares_kit_on":"Kit de reserva ativo ✓", "link_panels.spares_kit_on":"Kit de reserva ativo ✓",
"link_panels.stock_a_spare_optic_price":"Guardar um {optic} sobressalente <small>{price}</small>", "link_panels.stock_a_spare_optic_price":"Guardar um {optic} sobressalente <small>{price}</small>",
"link_panels.sys_level_n":"{sys} <small>nível {n}</small>", "link_panels.sys_level_n":"{sys} <small>nível {n}</small>",
"link_panels.take_it_off_standby":"Tirar da reserva",
"link_panels.there_s_no_ix_in_city":"Ainda não há IX em {city}. Funde um: as redes entram com o tempo, pagam pelas portas e fazem peering com você de graça.", "link_panels.there_s_no_ix_in_city":"Ainda não há IX em {city}. Funde um: as redes entram com o tempo, pagam pelas portas e fazem peering com você de graça.",
"link_panels.they_need_the_full_internet_your":"Eles querem a internet inteira. Seu alcance é de {pct}.", "link_panels.they_need_the_full_internet_your":"Eles querem a internet inteira. Seu alcance é de {pct}.",
"link_panels.this_fiber_is_dark_add_optics":"Esta fibra está apagada. Adicione ópticas abaixo para levar tráfego.", "link_panels.this_fiber_is_dark_add_optics":"Esta fibra está apagada. Adicione ópticas abaixo para levar tráfego.",

View file

@ -37,3 +37,5 @@ const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1));
const MET={prefer:{l:tr('common.prefer'),f:0.5},normal:{l:tr('common.normal'),f:1},avoid:{l:tr('common.avoid'),f:4},backup:{l:tr('common.backup_only'),f:60}}; const MET={prefer:{l:tr('common.prefer'),f:0.5},normal:{l:tr('common.normal'),f:1},avoid:{l:tr('common.avoid'),f:4},backup:{l:tr('common.backup_only'),f:60}};
const PREF={high:tr('common.prefer'),normal:tr('common.normal'),low:tr('common.backup_only')}; const PREF={high:tr('common.prefer'),normal:tr('common.normal'),low:tr('common.backup_only')};
const edgeKey=l=>l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a; const edgeKey=l=>l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;
// The routing metric of a city pair (edgeKey), set for every link between the two cities.
function pairMet(k){return (S.pairMet&&S.pairMet[k])||'normal';}

View file

@ -1,7 +1,9 @@
/* ---------- traceroute and looking glass ---------- */ /* ---------- traceroute and looking glass ---------- */
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x'; const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={}; function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} // Every link between two cities costs what the pair costs, as in compute(); the trace shows an active link over one on standby.
const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,(l.km+60)*MET[pairMet(k)].f);}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=pw[edgeKey(l)]+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}} const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};} const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};}
function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[]; function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[];

View file

@ -1,6 +1,6 @@
function newGame(name,home){ function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:3,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{}, ltv:2,t1v:3,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}};
} }

View file

@ -6,7 +6,10 @@ function compute(){
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={};
for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key]; for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[],res:0,ld:0,tr:null,pl:0};adj[ai].push([bi,e]);adj[bi].push([ai,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f*(TRX&&TRX.avoid.has(key)?60:1));e.lat=Math.min(e.lat,linkLat(l));} // The metric belongs to the city pair; links on standby add capacity that fills only after the others (#122).
if(!e){const f=MET[pairMet(key)].f;e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,scap:0,w:Infinity,lat:Infinity,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,f:f*(TRX&&TRX.avoid.has(key)?60:1)};adj[ai].push([bi,e]);adj[bi].push([ai,e]);}
const c=capOf(l),lt=linkLat(l);e.cap+=c;e.links.push(l);e.w=Math.min(e.w,(l.km+60)*e.f);if(l.standby){e.scap+=c;e.slat=Math.min(e.slat,lt);}else e.lat=Math.min(e.lat,lt);}
for(const k in edges){const e=edges[k];if(e.lat===Infinity)e.lat=e.slat;}
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by. // Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by.
// ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it). // ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it).
const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05; const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05;
@ -242,7 +245,8 @@ function compute(){
Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of t.g)rec.eg[k]=v; Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of t.g)rec.eg[k]=v;
for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});} for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});}
Object.defineProperty(R2,'efg',{value:efg});} Object.defineProperty(R2,'efg',{value:efg});}
for(const k in edges){const e=edges[k],ld=e.ld||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;} // Active links fill first, by capacity; standby links take what is left over.
for(const k in edges){const e=edges[k],ld=e.ld||0,ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;for(const l of e.links){const c=capOf(l);R2.load[l.id]=l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0);}}
R2.peerShare=R2.served>0?R2.peered/R2.served:0; R2.peerShare=R2.served>0?R2.peered/R2.served:0;
for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;} for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
// money // money

View file

@ -6,7 +6,7 @@ const num=(v,d=0)=>{v=+v;return Number.isFinite(v)?v:d;},int=(v,lo,hi,d)=>{v=Mat
function sanitize(s){ function sanitize(s){
const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};}; const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};};
['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr); ['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr);
['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach'].forEach(obj); ['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj);
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000); s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0); s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0);
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);} for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
@ -14,8 +14,13 @@ function sanitize(s){
for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;}
if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra';
const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40);
s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;}); s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;});
for(const l of s.links)repairSubUpgradeDates(l,s.day); for(const l of s.links)repairSubUpgradeDates(l,s.day);
/* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its
links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */
{const pm=s.pairMet,lo={};for(const l of s.links){if(l.metric!==undefined){const k=edgeKey(l),m=own(MET,l.metric)?l.metric:'normal';if(!lo[k]||MET[m].f<MET[lo[k]].f)lo[k]=m;}if(l.standby!==true)delete l.standby;}
for(const l of s.links){const k=edgeKey(l);if(lo[k]&&l.metric===undefined)lo[k]='normal';delete l.metric;}
for(const k in lo)pm[k]=lo[k];const ks=new Set(s.links.map(edgeKey));for(const k of Object.keys(pm))if(!ks.has(k)||!own(MET,pm[k])||pm[k]==='normal')delete pm[k];}
const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;
s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t)); s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t));
s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x));

View file

@ -3,7 +3,7 @@ Object.assign(ACT,{
decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();}, decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();},
decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();},
decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();},
rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');}}S.links=S.links.filter(l=>l.id!==id);UI.sel=null;UI.confirm=null;after();}, rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');}}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();},
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;if(i.slow&&i.rushed)return;if(!spend(i.cost))return; fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;if(i.slow&&i.rushed)return;if(!spend(i.cost))return;
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();}, if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
@ -26,8 +26,9 @@ Object.assign(ACT,{
const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal(); const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal();
toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();}, toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();},
upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('links.fabric_port_in_city_is_full',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();}, upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('links.fabric_port_in_city_is_full',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();},
cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();}, cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);prunePairMet();const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();},
setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();},
setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();}, setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;const m=S.pairMet||(S.pairMet={}),k=edgeKey(l);if(v==='normal')delete m[k];else m[k]=v;sfx('click');after();},
setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();},
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},
}); });

View file

@ -4,6 +4,8 @@ function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind
// Which route a new wave joins: null = a new diverse route. 'same' is the old two-way choice (the main route). // Which route a new wave joins: null = a new diverse route. 'same' is the old two-way choice (the main route).
function routeJoin(a,b){const ts=landTrenches(a,b),r=UI.route||'';if(r==='same')return ts[0]||null;if(r.startsWith('t:'))return ts.find(t=>t.k===r.slice(2))||null;return null;} function routeJoin(a,b){const ts=landTrenches(a,b),r=UI.route||'';if(r==='same')return ts[0]||null;if(r.startsWith('t:'))return ts.find(t=>t.k===r.slice(2))||null;return null;}
function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));}
// A city pair's metric goes with its last link, so a new link between the same cities starts on normal.
function prunePairMet(){const m=S.pairMet;if(!m)return;const k=new Set(S.links.map(edgeKey));for(const x of Object.keys(m))if(!k.has(x))delete m[x];}
// Short, busy subsea routes (London–Amsterdam, London–Paris) sell dark fiber pairs too. // Short, busy subsea routes (London–Amsterdam, London–Paris) sell dark fiber pairs too.
function subDfCable(a,b){return cablesOk(a,b).filter(c=>CAB[c.cid].df).sort((x,y)=>x.km-y.km)[0]||null;} function subDfCable(a,b){return cablesOk(a,b).filter(c=>CAB[c.cid].df).sort((x,y)=>x.km-y.km)[0]||null;}
function dfAllowed(a,b){if(isSub(a,b))return !!subDfCable(a,b);return cnCity(a)===cnCity(b)&&!uaePair(a,b)&&!landX(a,b);} function dfAllowed(a,b){if(isSub(a,b))return !!subDfCable(a,b);return cnCity(a)===cnCity(b)&&!uaePair(a,b)&&!landX(a,b);}

View file

@ -13,7 +13,7 @@ function decomModal(){const sel=[...(UI.decom||[])],im=decomImpact(sel),all=Obje
${left<1?`<p class="why">${tr('decommission.keep_at_least_one_pop')}</p>`:''} ${left<1?`<p class="why">${tr('decommission.keep_at_least_one_pop')}</p>`:''}
<div class="btns" style="margin-top:10px">${btn(sel.length?trn('decommission.decommission_n_pop_pay_fee',sel.length,{fee:fmt$(im.fee)}):tr('decommission.pick_a_pop'),'decomGo',{},'red',!sel.length||left<1)}${btn(tr('common.keep_them'),'closeModal',{},'ghost')}</div>`);} <div class="btns" style="margin-top:10px">${btn(sel.length?trn('decommission.decommission_n_pop_pay_fee',sel.length,{fee:fmt$(im.fee)}):tr('decommission.pick_a_pop'),'decomGo',{},'red',!sel.length||left<1)}${btn(tr('common.keep_them'),'closeModal',{},'ghost')}</div>`);}
function decommission(cities){const set=new Set(cities),im=decomImpact(cities),lids=new Set(im.links.map(l=>l.id)),bids=new Set(im.biz.map(b=>b.id)); function decommission(cities){const set=new Set(cities),im=decomImpact(cities),lids=new Set(im.links.map(l=>l.id)),bids=new Set(im.biz.map(b=>b.id));
S.links=S.links.filter(l=>!lids.has(l.id));S.biz=S.biz.filter(b=>!bids.has(b.id));S.offers=S.offers.filter(o=>!bCities(o).some(c=>set.has(c))); S.links=S.links.filter(l=>!lids.has(l.id));prunePairMet();S.biz=S.biz.filter(b=>!bids.has(b.id));S.offers=S.offers.filter(o=>!bCities(o).some(c=>set.has(c)));
S.transit=S.transit.filter(t=>!set.has(t.city));S.pni=S.pni.filter(x=>!set.has(x.city));S.caches=S.caches.filter(x=>!set.has(x.city));S.nni=(S.nni||[]).filter(x=>!set.has(x.city)); S.transit=S.transit.filter(t=>!set.has(t.city));S.pni=S.pni.filter(x=>!set.has(x.city));S.caches=S.caches.filter(x=>!set.has(x.city));S.nni=(S.nni||[]).filter(x=>!set.has(x.city));
for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);delete S.pops[c];} for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);delete S.pops[c];}
const rem=remoteCities();for(const x in S.ixp){const c=ixCity(x);if(!S.pops[c]&&!rem.includes(c)){delete S.ixp[x];delete S.rs[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}} const rem=remoteCities();for(const x in S.ixp){const c=ixCity(x);if(!S.pops[c]&&!rem.includes(c)){delete S.ixp[x];delete S.rs[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}}

View file

@ -51,8 +51,13 @@ function trafficSection(l){
if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`<p class="why">${tr('link_panels.biggest_feeder_egress_in_city_set',{egress:esc(d.lab),city:CITY[d.city].name})}</p>`;} if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`<p class="why">${tr('link_panels.biggest_feeder_egress_in_city_set',{egress:esc(d.lab),city:CITY[d.city].name})}</p>`;}
return h+`</section>`; return h+`</section>`;
} }
function metricSection(l){const cur=l.metric||'normal'; function metricSection(l){const cur=pairMet(edgeKey(l)),pl=pairLinks(l.a,l.b),sb=!!l.standby;
return `<section><h3>${tr('common.routing_metric')}</h3><p class="lead">${tr('link_panels.your_routers_pick_the_lowest_cost')}</p><div class="btns">${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}</div></section>`;} let h=`<section><h3>${tr('common.routing_metric')}</h3><p class="lead">${tr('link_panels.your_routers_pick_the_lowest_cost')}</p><div class="btns">${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}</div>`;
// Standby only means something next to another link; a link left on standby alone can still be taken off it.
if(pl.length>1||sb){const busy=(R.load[l.id]||0)>1e-3,alone=!pl.some(x=>x!==l&&!x.standby&&!linkDown(x));
const st=!sb?tr('link_panels.a_link_on_standby_carries_traffic'):!busy?tr('link_panels.on_standby_idle_while_the_other'):alone?tr('link_panels.on_standby_but_carrying_the_traffic'):tr('link_panels.on_standby_taking_the_overflow');
h+=`<h4 class="sub4">${tr('common.standby')}</h4><p class="note">${st}</p><div class="btns">${sb?btn(tr('link_panels.take_it_off_standby'),'setStandby',{id:l.id,on:0},'pink sm'):btn(tr('link_panels.put_this_link_on_standby'),'setStandby',{id:l.id,on:1},'ghost sm')}</div>`;}
return h+`</section>`;}
function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2;
let h=`<section><h3>${tr('link_panels.behind_the_great_firewall')}</h3><p class="lead">${tr('link_panels.mainland_china_plays_by_its_own',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}</p>`; let h=`<section><h3>${tr('link_panels.behind_the_great_firewall')}</h3><p class="lead">${tr('link_panels.mainland_china_plays_by_its_own',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}</p>`;
if(st==='none')h+=`<p class="lead">${tr('link_panels.foreign_networks_need_a_local_joint')}</p>${btn(tr('link_panels.apply_for_a_license_price_mo',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash<CN_LIC)}`; if(st==='none')h+=`<p class="lead">${tr('link_panels.foreign_networks_need_a_local_joint')}</p>${btn(tr('link_panels.apply_for_a_license_price_mo',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash<CN_LIC)}`;
@ -87,7 +92,7 @@ function dfPanel(l){
const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH); const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH);
h+=`</section><section><h3>${tr('common.line_system')}</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${tr('link_panels.n_amplifiers',{n:amps})}</b></div> h+=`</section><section><h3>${tr('common.line_system')}</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${tr('link_panels.n_amplifiers',{n:amps})}</b></div>
<div class="kv"><span>${tr('common.regen_sites')}</span><b>${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}</b></div><p class="note">${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}</p>${l.sub&&l.own?`<p class="note">${tr('link_panels.no_regen_sites_in_the_middle')}</p>`:`<div class="btns">${rg<REGEN_MAX?btn(tr('link_panels.regen_site_price',{price:fmt$(rgAdd)}),'regen',{id:l.id,d:1},'sm',S.cash<rgAdd):''}${rg?btn(tr('common.regen_site'),'regen',{id:l.id,d:-1},'ghost sm'):''}</div>`}<p class="note">${esc(sysD.blurb)}</p><div class="btns">${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return T.lvl>lvl()?btn(tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'upSys',{id:l.id},'sm',true):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash<c);})()}${pairBtn(l)}${btn(l.spares?tr('link_panels.spares_kit_on'):tr('link_panels.keep_a_spares_kit_price_mo',{price:fmt$(Math.round(150+(l.ch||[]).length*80))}),'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">${tr('link_panels.spare_optics_and_amplifier_cards_on')}</p></section>`; <div class="kv"><span>${tr('common.regen_sites')}</span><b>${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}</b></div><p class="note">${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}</p>${l.sub&&l.own?`<p class="note">${tr('link_panels.no_regen_sites_in_the_middle')}</p>`:`<div class="btns">${rg<REGEN_MAX?btn(tr('link_panels.regen_site_price',{price:fmt$(rgAdd)}),'regen',{id:l.id,d:1},'sm',S.cash<rgAdd):''}${rg?btn(tr('common.regen_site'),'regen',{id:l.id,d:-1},'ghost sm'):''}</div>`}<p class="note">${esc(sysD.blurb)}</p><div class="btns">${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return T.lvl>lvl()?btn(tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'upSys',{id:l.id},'sm',true):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash<c);})()}${pairBtn(l)}${btn(l.spares?tr('link_panels.spares_kit_on'):tr('link_panels.keep_a_spares_kit_price_mo',{price:fmt$(Math.round(150+(l.ch||[]).length*80))}),'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">${tr('link_panels.spare_optics_and_amplifier_cards_on')}</p></section>`;
{const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`<section><h3>${tr('common.redundancy')}</h3><p class="lead">${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}</p>${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${esc(capName(x))} ${linkDown(x)?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}</div><div class="meta">${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}</div></div>${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')}<div class="btns">${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}</div></section>`;} {const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`<section><h3>${tr('common.redundancy')}</h3><p class="lead">${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}</p>${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${esc(capName(x))} ${linkDown(x)?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}${x.standby?' <span class="tag st">'+tr('common.standby')+'</span>':''}</div><div class="meta">${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}</div></div>${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')}<div class="btns">${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}</div></section>`;}
h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):(l.own?tr('link_panels.abandon_the_fiber'):tr('link_panels.cancel_the_iru')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`<p class="note">${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}</p>`:''}</section></div>`; h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):(l.own?tr('link_panels.abandon_the_fiber'):tr('link_panels.cancel_the_iru')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`<p class="note">${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}</p>`:''}</section></div>`;
return h; return h;
} }

View file

@ -27,7 +27,7 @@ function drawFrame(now){
// links // links
const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY; const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY;
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc'; const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);let lab=null; const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);let lab=null;
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length; const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length;
if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);} if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);}
@ -39,8 +39,8 @@ function drawFrame(now){
const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i<np;i++)ctx.lineTo(SX[i],SY[i]);}; const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i<np;i++)ctx.lineTo(SX[i],SY[i]);};
ctx.lineCap='round';ctx.lineJoin='round'; ctx.lineCap='round';ctx.lineJoin='round';
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();} if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:[]);path();ctx.stroke(); ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[]);path();ctx.stroke();
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]); ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
// Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again. // Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again.
if(df&&!bld&&!dark&&!busy){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);} if(df&&!bld&&!dark&&!busy){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);}
const at=t=>polyAtXY(SX,SY,gm.cum,t); const at=t=>polyAtXY(SX,SY,gm.cum,t);

View file

@ -1250,6 +1250,7 @@
"common.spreadsheet_ipam":"Spreadsheet IPAM", "common.spreadsheet_ipam":"Spreadsheet IPAM",
"common.stage_six":"Stage Six", "common.stage_six":"Stage Six",
"common.standard":"Standard", "common.standard":"Standard",
"common.standby":"Standby",
"common.start_a_new_network":"Start a new network", "common.start_a_new_network":"Start a new network",
"common.start_building":"Start building", "common.start_building":"Start building",
"common.start_construction":"Start construction", "common.start_construction":"Start construction",
@ -2093,6 +2094,7 @@
"link_modal.waves_on_the_same_route_share":"Waves on the same route share its fate: one backhoe cuts them all.", "link_modal.waves_on_the_same_route_share":"Waves on the same route share its fate: one backhoe cuts them all.",
"link_modal.you_already_have_n_link_here":{"one":"You already have {n} link here ({list}). Parallel links add capacity. How should this one be routed?","other":"You already have {n} links here ({list}). Parallel links add capacity. How should this one be routed?"}, "link_modal.you_already_have_n_link_here":{"one":"You already have {n} link here ({list}). Parallel links add capacity. How should this one be routed?","other":"You already have {n} links here ({list}). Parallel links add capacity. How should this one be routed?"},
"link_panels.a_bigger_fabric_carries_more_traffic":"A bigger fabric carries more traffic and has room for more members. Your router here still has to keep up.", "link_panels.a_bigger_fabric_carries_more_traffic":"A bigger fabric carries more traffic and has room for more members. Your router here still has to keep up.",
"link_panels.a_link_on_standby_carries_traffic":"A link on standby carries traffic only when the other links between these cities are full or down.",
"link_panels.a_regen_site_turns_the_light":"A regen site turns the light back into bits halfway and sends it on fresh, so optics only have to reach the next site. Each needs a regen card for every lit channel. {price}/mo per site for the hut.", "link_panels.a_regen_site_turns_the_light":"A regen site turns the light back into bits halfway and sends it on fresh, so optics only have to reach the next site. Each needs a regen card for every lit channel. {price}/mo per site for the hut.",
"link_panels.abandon_the_fiber":"Abandon the fiber", "link_panels.abandon_the_fiber":"Abandon the fiber",
"link_panels.add_parallel_link":"Add parallel link", "link_panels.add_parallel_link":"Add parallel link",
@ -2152,6 +2154,9 @@
"link_panels.not_present_in_any_of_your":"Not present in any of your cities yet", "link_panels.not_present_in_any_of_your":"Not present in any of your cities yet",
"link_panels.nothing_spare_to_sell_on_this":"Nothing spare to sell on this fiber right now.", "link_panels.nothing_spare_to_sell_on_this":"Nothing spare to sell on this fiber right now.",
"link_panels.off_while_your_peering_policy_is":"Off while your peering policy is {pol}", "link_panels.off_while_your_peering_policy_is":"Off while your peering policy is {pol}",
"link_panels.on_standby_but_carrying_the_traffic":"On standby, but carrying the traffic: no active link between these cities is up.",
"link_panels.on_standby_idle_while_the_other":"On standby: idle while the other links between these cities have room.",
"link_panels.on_standby_taking_the_overflow":"On standby: taking the overflow, because the other links between these cities are full.",
"link_panels.open_peer_but_not_on_any":"Open peer, but not on any IX where you have a POP. Nearest: {city}", "link_panels.open_peer_but_not_on_any":"Open peer, but not on any IX where you have a POP. Nearest: {city}",
"link_panels.open_peer_but_not_on_any_bfbb":"Open peer, but not on any IX where you have a POP", "link_panels.open_peer_but_not_on_any_bfbb":"Open peer, but not on any IX where you have a POP",
"link_panels.open_peer_join_the_route_server":"Open peer: join the route server at {ix}", "link_panels.open_peer_join_the_route_server":"Open peer: join the route server at {ix}",
@ -2169,6 +2174,7 @@
"link_panels.ports_at_p_of_the_usual":"Ports at {p}% of the usual price.", "link_panels.ports_at_p_of_the_usual":"Ports at {p}% of the usual price.",
"link_panels.ports_up_to_port_are_free":"Ports up to {port} are free.", "link_panels.ports_up_to_port_are_free":"Ports up to {port} are free.",
"link_panels.price_n_days":"{price} · {n} days", "link_panels.price_n_days":"{price} · {n} days",
"link_panels.put_this_link_on_standby":"Put this link on standby",
"link_panels.ready_for_a_pni_in_city":"Ready for a PNI in {city}", "link_panels.ready_for_a_pni_in_city":"Ready for a PNI in {city}",
"link_panels.ready_in_n_days":"Ready in {n} days", "link_panels.ready_in_n_days":"Ready in {n} days",
"link_panels.really_give_it_up":"Really give it up?", "link_panels.really_give_it_up":"Really give it up?",
@ -2191,6 +2197,7 @@
"link_panels.spares_kit_on":"Spares kit on ✓", "link_panels.spares_kit_on":"Spares kit on ✓",
"link_panels.stock_a_spare_optic_price":"Stock a spare {optic} <small>{price}</small>", "link_panels.stock_a_spare_optic_price":"Stock a spare {optic} <small>{price}</small>",
"link_panels.sys_level_n":"{sys} <small>level {n}</small>", "link_panels.sys_level_n":"{sys} <small>level {n}</small>",
"link_panels.take_it_off_standby":"Take it off standby",
"link_panels.there_s_no_ix_in_city":"There's no IX in {city} yet. Found one: networks join over time, pay you for ports, and peer with you for free.", "link_panels.there_s_no_ix_in_city":"There's no IX in {city} yet. Found one: networks join over time, pay you for ports, and peer with you for free.",
"link_panels.they_need_the_full_internet_your":"They need the full internet. Your reach is {pct}.", "link_panels.they_need_the_full_internet_your":"They need the full internet. Your reach is {pct}.",
"link_panels.this_fiber_is_dark_add_optics":"This fiber is dark. Add optics below to carry traffic.", "link_panels.this_fiber_is_dark_add_optics":"This fiber is dark. Add optics below to carry traffic.",

139
tests/link-metrics.test.js Normal file
View file

@ -0,0 +1,139 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Waves between Frankfurt and Amsterdam (tier 3 is 800G, tier 0 is 10G), transit in Amsterdam, eyeballs in Frankfurt.
function setup(ev, tiers = [3, 3]) {
ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'ams',net:'lvl',tier:3})");
tiers.forEach((t, i) => ev(`UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:${t}});closeModal();S.links[S.links.length-1].tag=${i}`));
ev("var L=i=>S.links.find(l=>l.tag===i),L1=L(0),L2=L(1);compute()");
}
const load_ = (ev, x) => ev(`R.load[${x}.id]||0`);
const body = dom => dom.window.document.body.textContent;
test('#122 the routing metric belongs to the city pair', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.setMetric({id:L2.id,v:'avoid'})");
assert.equal(ev("S.pairMet['ams|fra']"), 'avoid');
ev("ACT.selLink({id:L1.id});renderAll()");
assert.ok(ev("[...document.querySelectorAll('[data-act=\"setMetric\"]')].some(b=>b.className.includes('pink')&&/Avoid/.test(b.textContent))"), 'the other link shows the same metric');
ev("ACT.setMetric({id:L1.id,v:'normal'})");
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.deepEqual(errors, []);
});
test('#122 a link on standby idles while the others have room and takes over when they fail', () => {
const { ev, dom, errors } = load();
setup(ev);
const total = ev("R.served");
assert.ok(load_(ev, 'L1') > 0 && load_(ev, 'L2') > 0, 'active links share the load');
ev("ACT.setStandby({id:L2.id,on:1});compute()");
assert.equal(ev("L2.standby"), true);
assert.ok(load_(ev, 'L1') > 0);
assert.equal(load_(ev, 'L2'), 0, 'standby link idles');
assert.ok(Math.abs(ev("R.served") - total) < 1e-6, 'nothing is lost');
ev("ACT.selLink({id:L2.id});renderAll()");
assert.match(body(dom), /On standby: idle while the other links/);
ev("L1.cut=S.day+5;compute();renderAll()");
assert.ok(load_(ev, 'L2') > 0, 'standby link takes over when the active one is cut');
assert.match(body(dom), /On standby, but carrying the traffic/);
// Every link on standby: they share the traffic like active ones, and the note does not claim the others are down.
ev("L1.cut=0;ACT.setStandby({id:L1.id,on:1});compute();renderAll()");
assert.ok(load_(ev, 'L1') > 0 && load_(ev, 'L2') > 0);
assert.match(body(dom), /no active link between these cities is up/);
ev("ACT.setStandby({id:L2.id,on:0})");
assert.equal(ev("'standby' in L2"), false);
assert.deepEqual(errors, []);
});
test('#122 a standby link takes the overflow when the active links are full', () => {
const { ev, dom, errors } = load();
setup(ev, [0, 3]); // 10G active, 800G next to it
const total = ev("R.served");
ev("ACT.setStandby({id:L2.id,on:1});compute()");
const cap = ev("capOf(L1)");
assert.ok(Math.abs(load_(ev, 'L1') - cap) < 1e-6, 'the active link fills up first');
assert.ok(load_(ev, 'L2') > 0, 'the rest spills onto the standby link');
assert.ok(Math.abs(ev("R.served") - total) < 1e-6, 'standby capacity is never wasted');
ev("ACT.selLink({id:L2.id});renderAll()");
assert.match(body(dom), /taking the overflow/);
assert.deepEqual(errors, []);
});
test('#122 the order links are built in does not change where traffic goes', () => {
const tiers = [3, 0, 3], standby = [true, false, false], seen = new Set();
for (const order of [[0, 1, 2], [2, 1, 0], [1, 0, 2], [2, 0, 1]]) {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'ams',net:'lvl',tier:3})");
for (const i of order) ev(`UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:${tiers[i]}});closeModal();const l=S.links[S.links.length-1];l.tag=${i};if(${standby[i]})ACT.setStandby({id:l.id,on:1})`);
ev("ACT.setMetric({id:S.links[0].id,v:'prefer'});compute()");
seen.add(ev("JSON.stringify([0,1,2].map(i=>Math.round((R.load[S.links.find(l=>l.tag===i).id]||0)*1e6)))"));
assert.deepEqual(errors, []);
}
assert.equal(seen.size, 1, [...seen].join(' vs '));
});
test('#122 a new link between the same cities adds capacity and keeps the pair metric', () => {
const { ev, errors } = load();
setup(ev, [0]);
ev("ACT.setMetric({id:L1.id,v:'avoid'});ACT.setStandby({id:L1.id,on:1});compute()");
const before = ev("R.served");
ev("UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:3});closeModal();compute()");
const nl = "S.links[S.links.length-1]";
assert.equal(ev(`'standby' in ${nl}`), false, 'a new link starts active');
assert.equal(ev("pairMet('ams|fra')"), 'avoid');
assert.ok(ev("R.served") > before, 'more capacity, more traffic');
// The metric leaves with the last link, so a fresh link later starts on normal.
for (const id of ev("S.links.map(l=>l.id)")) ev(`UI.confirm=null;ACT.rmLink({id:'${id}'});ACT.rmLink({id:'${id}'})`);
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.deepEqual(errors, []);
});
test('#122 old saves keep routing as before: per-link metrics become the pair metric', () => {
const { ev, errors } = load();
setup(ev);
// Every link on avoid: the pair is on avoid.
ev("delete S.pairMet;L1.metric='avoid';L2.metric='avoid';S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("S.pairMet['ams|fra']"), 'avoid');
assert.equal(ev("S.links.some(l=>'metric' in l)"), false);
// Mixed metrics routed at the lowest one, all links carrying: no standby, normal.
ev("S.pairMet={};S.links[0].metric='backup';S.links[1].standby='yes';S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.equal(ev("S.links.some(l=>'standby' in l||'metric' in l)"), false);
assert.ok(ev("S.links.every(l=>R.load[l.id]>0)"));
// Junk in the new field is dropped.
ev("S.pairMet={'ams|fra':'warp','fra|lon':'avoid'};S=migrate(JSON.parse(JSON.stringify(S)))");
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pairMet)")), {});
assert.deepEqual(errors, []);
});
test('#122 traceroute shows an active link, not one on standby', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.setStandby({id:L1.id,on:1})");
assert.equal(ev("trPaths('ams').path('fra')[0].l.id===L2.id"), true);
ev("ACT.setStandby({id:L1.id,on:0});ACT.setStandby({id:L2.id,on:1})");
assert.equal(ev("trPaths('ams').path('fra')[0].l.id===L1.id"), true);
assert.deepEqual(errors, []);
});
test('#122 the standby button shows next to another link, on desktop and phone', () => {
const { ev, dom, errors } = load();
setup(ev);
for (const w of [1280, 390]) {
ev(`window.innerWidth=${w};ACT.selLink({id:L1.id});renderAll()`);
const b = dom.window.document.querySelector('[data-act="setStandby"]');
assert.ok(b, `standby button at ${w}px`);
assert.match(b.textContent, /Put this link on standby/);
}
ev("S.links=S.links.filter(l=>l!==L2);ACT.selLink({id:L1.id});renderAll()");
assert.equal(dom.window.document.querySelector('[data-act="setStandby"]'), null, 'nothing to stand by for');
ev("L1.standby=true;renderAll()");
assert.match(dom.window.document.querySelector('[data-act="setStandby"]').textContent, /Take it off standby/);
assert.deepEqual(errors, []);
});